package com.quanyan.place.service.impl;

import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_BASE;
import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_COMBINE;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import com.quanyan.place.entity.*;
import com.quanyan.place.mapper.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.PlaceTools;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.common.utils.TimeUtils;
import com.quanyan.common.utils.ValidatorUtils;
import com.quanyan.place.biz.ISearchService;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.apiresp.RespBizPlaceTrafficInfo;
import com.quanyan.place.entity.apiresp.RespFieldScale;
import com.quanyan.place.entity.apiresp.RespPlaceFieldScales;
import com.quanyan.place.entity.apiresp.RespPlaceInfo;
import com.quanyan.place.entity.vo.MqPlaceGroupId;
import com.quanyan.place.entity.vo.PlaceCategoryVo;
import com.quanyan.place.entity.vo.PlaceCommonDataVo;
import com.quanyan.place.entity.vo.PlaceDistribution;
import com.quanyan.place.entity.vo.PlaceFromDataVo;
import com.quanyan.place.entity.vo.PlaceKpiInfo;
import com.quanyan.place.entity.vo.PlaceNewInfo;
import com.quanyan.place.entity.vo.PlaceOperationRuleVo;
import com.quanyan.place.entity.vo.PlaceSaleDistribution;
import com.quanyan.place.entity.vo.PlaceUnitSalePlan;
import com.quanyan.place.entity.vo.PlaceUnitSalePlanVo;
import com.quanyan.place.entity.vo.PlaceUnitTime;
import com.quanyan.place.entity.vo.ReqPlaceSearch;
import com.quanyan.place.entity.vo.ReqPlaceUnitSearch;
import com.quanyan.place.entity.vo.ReqSupplierSearchVo;
import com.quanyan.place.entity.vo.TbBizPlaceUnitVo;
import com.quanyan.place.entity.vo.VPlaceBusiness;
import com.quanyan.place.entity.vo.VPlaceSale;
import com.quanyan.place.entity.vo.VPlaceTime;
import com.quanyan.place.service.EmployeeService;
import com.quanyan.place.service.PeriodService;
import com.quanyan.place.service.PlaceInnerService;
import com.quanyan.place.service.RepresentService;
import com.quanyan.place.service.TbBizPlacePeriodService;
import com.quanyan.place.thread.ModifyPlaceUnitNameThread;
import com.quanyan.place.thread.SyncSalePlanThread;
import com.quanyan.place.thread.UpdateSalePlanThread;
import com.quanyan.place.utils.PlaceUtil;
import com.quanyan.place.wrapper.impl.MqPlaceProductWrapperImpl;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.search.service.PlaceSearchService;
import com.quanyan.search.service.impl.PlaceSearchServiceImpl;

/**
 * 场馆内部Serivice实现类
 *
 * Created by yangyun on 2016/4/19.
 */
@Service("placeInnerService")
public class PlaceInnerServiceImpl implements PlaceInnerService {

    @Autowired
    TbBizPlaceMapper placeMapper;

    @Autowired
    TbBizPlaceUnitMapper placeUnitMapper;

    @Autowired
    TbBizPlaceUnitCombineMapper placeUnitCombineMapper;

    @Autowired
    VPlaceMapper vPlaceMapper;

    @Autowired
    TbBizPlaceAttachMapper tbBizPlaceAttachMapper;

    @Autowired
    PlaceMapper pMapper;

    @Autowired
    TbBizPlaceUnitTimeMapper placeUnitTimeMapper;

    @Autowired
    private TbBizPlaceBuyContractDetailMapper placeBuyContractDetailMapper;

    @Autowired
    DictMapper dictMapper;

    @Autowired
    TbSupplierMapper tbSupplierMapper;

    @Autowired
    TbProvinceMapper tbProvinceMapper;

    @Autowired
    TbCityMapper tbCityMapper;

    @Autowired
    TbDistrictMapper tbDistrictMapper;

    @Autowired
    TbBizPlaceUnitStatisticsMapper unitStatisticsMapper;

    @Autowired
    TbBizPlaceUnitSalePlanMainMapper placeUnitSalePlanMainMapper;

    @Autowired
    TbBizPlaceUnitSalePlanMapper placeUnitSalePlanMapper;

    @Autowired
    TbBizPlaceCategoryMapper tbBizPlaceCategoryMapper;

    @Autowired
    TbBizPlaceRuleMapper tbBizPlaceRuleMapper;

    @Autowired
    TbBizPlaceAuthUserMapper tbBizPlaceAuthUserMapper;

    @Autowired
    PlaceUnitSalePlanMapper salePlanMapper;

    @Autowired
    TbBizPlaceMapper tbBizPlaceMapper;

    @Autowired
    CagetoryMapper categoryMapper;

    @Autowired
    TbAdminUserMapper adminUserMapper;

    @Autowired
    TbPlaceImageMapper tbPlaceImageMapper;

    @Autowired
    PlaceAttachMapper placeAttachMapper;

    @Autowired
    PlaceUnitMapper placeUnitListMapper;

    @Autowired
    TbBizPlacePeriodService tbBizPlacePeriodService;

    @Autowired
    ISearchService searchService;

    @Autowired
    EmployeeService employeeService;

    @Autowired
    PeriodService periodService;

    @Autowired
    RepresentService representService;

    private Map<Integer, Cagetory> categoryMap;

    @Autowired
    private PlaceRedisTemplate placeCache;

    @Autowired
    private TbBizPlaceRepresentMapper tbBizPlaceRepresentMapper;

    @Autowired
    private TbBizPlacePeriodMapper tbBizPlacePeriodMapper;

    @Autowired
    TbBizPlaceUnitCombineMapper pucMapper;

    static Map<String,String> placeCommonDataMap = new ConcurrentHashMap<String,String>();

    private Logger logger = LoggerFactory.getLogger(PlaceInnerServiceImpl.class);

    private static ExecutorService executorService = Executors.newSingleThreadExecutor();

    private static ScheduledExecutorService exec = new ScheduledThreadPoolExecutor(1);

    private static ExecutorService updateExecutorPlaceUnitNameService = Executors.newSingleThreadExecutor();

    @Autowired
    private TbBizPlaceUnitSalePlanMapper tbBizPlaceUnitSalePlanMapper;
    @Autowired
    private TbBizPlaceUnitSalePlanMainMapper tbBizPlaceUnitSalePlanMainMapper;

    @Value("${c.service.url}")
    public String cAddress;

    @Value("${SOLRCLOUD.SERVER.URL}")
    private String solrUrl;

    @Value("${place.admin.uid}")
    private Integer placeAdminUser;

    @Autowired
    MqPlaceProductWrapperImpl mqPlaceProductWrapper;

    @Autowired
    TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;

    @Autowired
    TbBizPlaceOrderMapper tbBizPlaceOrderMapper;

    @Override
    public PageObj<List<PlaceNewInfo>> getPlaceList(ReqPlaceSearch reqPlaceSearch) {
        Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        String keywords = null;
        Integer cityId = null;
        Integer districtId = null;
        Byte isSign = null;
        Byte categoryId = null;
        Byte businessMode = null;
        Byte isShelves = null;
        Integer buyType=null;
        if (reqPlaceSearch != null) {
            pageNum = reqPlaceSearch.getPageNum();
            pageSize = reqPlaceSearch.getPageSize();
            keywords = reqPlaceSearch.getKey();
            cityId = reqPlaceSearch.getCityId();
            districtId = reqPlaceSearch.getDistrictId();
            isSign = reqPlaceSearch.getIsSign();
            categoryId = reqPlaceSearch.getCategoryId();
            businessMode = reqPlaceSearch.getBusinessMode();
            isShelves = reqPlaceSearch.getIsShelves();
            buyType=reqPlaceSearch.getBuyType();
        }

        List<PlaceNewInfo> placeList = new ArrayList<PlaceNewInfo>();
        int totalNum = vPlaceMapper.countPlace(keywords, cityId, districtId, isSign, categoryId, businessMode, isShelves,buyType);

        List<RespPlaceInfo> bizPlaceList = vPlaceMapper.getPlaceList(pageNum * pageSize, pageSize, keywords, cityId, districtId, isSign, categoryId, businessMode, isShelves,buyType);
        Map<String, String> dictMap = getDictDisplayName(PlaceConstants.DICT_TYPE_21);
        //TbBizPlaceEmployee employ = employeeService.getEmployeeByUid(reqPlaceSearch.getUid());
        for (RespPlaceInfo bizPlace : bizPlaceList) {
            TbBizPlaceAttach placeAttach = this.getBizPlaceAttach(bizPlace.getId());
            PlaceNewInfo placeInfo = new PlaceNewInfo();
            placeInfo.setPlaceMain(bizPlace);
            Integer unitNum = this.countPlaceUnitByPlaceId(bizPlace.getId());
            placeInfo.setUnitNum(unitNum);  // 场地片数
            PlaceCategoryVo placeCategory = this.getPlaceCategory(bizPlace.getId());
            if (null != placeCategory) {
                Set<Integer> categoryIdSet = placeCategory.getCategoryIdSet();
                if (null != categoryIdSet && !categoryIdSet.isEmpty()) {
                    if (categoryIdSet.size() > 1) {
                        placeInfo.setCategoryTypeName("综合");
                    } else {
                        Iterator<Integer> it = categoryIdSet.iterator();
                        Integer catergoryId = it.next();
                        placeInfo.setCategoryTypeName(this.getCategoryNameById(catergoryId));
                    }
                }
            }
            if (placeAttach != null) {
                //placeInfo.setRestOperateYears(placeAttach.getRemainTime()); //   剩余年限
                //placeInfo.setSaleTimeByWeek(this.computeSaleTimeInWeek(placeAttach, unitNum));  // 周销售时长
                placeInfo.setManageTypeName(dictMap.get(placeAttach.getManageType()));
            }
            Integer count = vPlaceMapper.countSalePlanMain(bizPlace.getId(), null);
            if (null != count && count > 0){
                placeInfo.setIsPriced(Constants.BYTE_ONE);
            } else {
                placeInfo.setIsPriced(Constants.BYTE_ZERO);
            }
            if (bizPlace.getBuyType()!=null){
                String [] buyTypeArr =bizPlace.getBuyType().split(",");
                List<String> strList=new ArrayList<>();
                for (int i=0;i<buyTypeArr.length;i++){
                   strList.add(buyTypeArr[i]);
                }
                placeInfo.setStrList(strList);
            }
            // 商务考核相关功能已不需要，屏蔽 -- 坑爹的产品需求
            // placeInfo.setPrimeTimeByWeek(this.computePrimeTimeByWeek(bizPlace.getId()));
           /* if(reqPlaceSearch.getUid()!=null) {
                if(null != employ){
                    if(employ.getCityId().equals(bizPlace.getCityId())){
                        if (employ.getTitle() != null) {
                           //显示锁定按钮
                            if (PlaceConstants.SEA_AREA_TYPE_PUBLIC.equals(bizPlace.getSeaAreaType())&&PlaceConstants.IS_SIGN_NO.equals(bizPlace.getIsSign())) {
                                placeInfo.setLockShowSet(1);//1：显示。0：不显示
                            } else {
                                placeInfo.setLockShowSet(0);
                            }
                            //显示延长时效按钮
                            if (PlaceConstants.TITLE_BUSSINESS_CITY_MANAGER.equals(employ.getTitle()) && PlaceConstants.SEA_AREA_TYPE_PRIVATE.equals(bizPlace.getSeaAreaType())&&PlaceConstants.IS_SIGN_NO.equals(bizPlace.getIsSign())) {
                                placeInfo.setIsShowSet(1);//1：显示。0：不显示
                            } else {
                                placeInfo.setIsShowSet(0);
                            }
                        }
                    }
                }
            }
            TbBizPlaceRepresent repVo=representService.getRepresentInfoByPlaceId(bizPlace.getId(),1);
            if (repVo!=null){
                placeInfo.setBussinessRepresent(repVo.getBusinessRepresent());
            }
            */
                placeList.add(placeInfo);
            }
        PageObj<List<PlaceNewInfo>> result = PageObj.create(totalNum, pageNum, pageSize, placeList);
        return result;
    }

    /**
     * 根据栏目id获取栏目名称
     *
     * @param categoryId
     * @return
     */
    public String getCategoryNameById(Integer categoryId) {
        if (null == categoryMap) {
            categoryMap = this.getCategoryMap();
        }
        if (null != categoryMap && categoryMap.containsKey(categoryId)) {
            return categoryMap.get(categoryId).getName();
        } else {
            return "";
        }
    }

    /**
     * 获取栏目（运动项目）
     *
     * @return
     */
    public Map<Integer, Cagetory> getCategoryMap() {
        String key = RedisConstants.PLACE_FAMILY_KEY + "CATEGORY";
        // 从Redis取出栏目信息（运动项目）
        Map<Integer, Cagetory> categoryMap = (Map<Integer, Cagetory>) placeCache.get(key);
        if (categoryMap == null || categoryMap.isEmpty()) {
            CagetoryExample cagetoryExample = new CagetoryExample();
            cagetoryExample.createCriteria().andIsDeleteEqualTo(Constants.IS_DELETE_FALSE)
                    .andIsEnableEqualTo(Constants.IS_ENABLE_TRUE);
            List<Cagetory> categoryList = categoryMapper.selectByExample(cagetoryExample);
            categoryMap = new HashMap<Integer, Cagetory>();
            for (Cagetory category : categoryList) {
                categoryMap.put(category.getId(), category);
            }
            // 放入Redis
            placeCache.set(key, categoryMap);
        }
        return categoryMap;
    }

    /**
     * 商务场馆分布图数据取得
     *
     * @param cityId
     * @param districtId
     * @param categoryId
     * @return
     */
    @Override
    public PlaceDistribution getPlaceDistribuctionGroup(Integer cityId,
                                                        Integer categoryId,
                                                        Integer districtId,
                                                        Integer primeType,
                                                        Integer isSign) {

        List<VPlaceBusiness> placeList = vPlaceMapper.selectPlaceGroupData(cityId, categoryId, districtId, primeType, isSign);
        List<VPlaceBusiness> filtedResult = null;
        PlaceDistribution placeDistribution = new PlaceDistribution();
        Integer unitSignNum = 0;
        Integer signNum = 0;
        Map<Integer, VPlaceBusiness> placeMap = new HashMap<Integer, VPlaceBusiness>();
        if (null == placeList) {
            return placeDistribution;
        }
        for (VPlaceBusiness place : placeList) {
            // 以防存储是检验不严格，查询时不在合理经纬度范围内的排除
            if (place.getLat() <= 0 || place.getLng() <= 0 ||
                    place.getLat() > PlaceConstants.CHINA_MAX_LAT ||
                    place.getLat() < PlaceConstants.CHINA_MIN_LAT ||
                    place.getLng() > PlaceConstants.CHINA_MAX_LNG ||
                    place.getLng() < PlaceConstants.CHINA_MIN_LNG) {
                continue;
            }
            if (!placeMap.containsKey(place.getPlaceId())) {
                // 统一场馆的多片场地，地图上只显示一个坐标
                placeMap.put(place.getPlaceId(), place);
                if (place.getIsSign() != null && place.getIsSign() == 1) {
                    signNum += 1;  // 场地已签约数量
                }

            }
            if (place.getUnitIsSign() != null && Constants.BYTE_ONE == place.getUnitIsSign()) {
                unitSignNum += 1;  // 片场已签约数量
            }

        }
        filtedResult = new ArrayList<VPlaceBusiness>(placeMap.values());
        placeDistribution.setPlaceList(filtedResult);
        if (placeMap != null && placeMap.size() > 0) {
            placeDistribution.setPlaceNum(placeMap.size());
            placeDistribution.setIsSignPlaceNum(signNum); // 签约的场馆数量
            placeDistribution.setNotSignPlaceNum(placeMap.size() - signNum); // 未签约的场馆数量
        } else {
            placeDistribution.setPlaceNum(0);
            placeDistribution.setIsSignPlaceNum(0); // 签约的场馆数量
            placeDistribution.setNotSignPlaceNum(0); // 未签约的场馆数量
        }
        if (CollectionUtils.isNotEmpty(placeList)) {
            placeDistribution.setPlaceUnitNum(placeList.size());  // 场馆总片数
            placeDistribution.setIsSignUnitNum(unitSignNum); // 签约的场地片数
            placeDistribution.setNotSignUnitNum(placeList.size() - unitSignNum); // 未签约的场地片数
        } else {
            placeDistribution.setPlaceUnitNum(0);
            placeDistribution.setIsSignUnitNum(0);
            placeDistribution.setNotSignUnitNum(0);
        }
        // 统计满足地图查询条件的所有场馆时段统计数（这需求挺坑爹，无实际意义）
        List<TbBizPlaceUnitStatistics> statisticsResult = vPlaceMapper.getPlaceUnitStatistics(cityId, districtId, categoryId);
        if (statisticsResult != null && statisticsResult.size() > 0) {
            TbBizPlaceUnitStatistics unitStatistics = statisticsResult.get(0);
            if (unitStatistics != null) {
                placeDistribution.setWeekHourNum(unitStatistics.getWeekHourNum());
                placeDistribution.setWeekSignHourNum(unitStatistics.getWeekSignHourNum());
                placeDistribution.setWeekPrimeHourNum(unitStatistics.getWeekPrimeHourNum());
                placeDistribution.setWeekSignPrimeHourNum(unitStatistics.getWeekSignPrimeHourNum());
                if (unitStatistics.getWeekHourNum() != null
                        && unitStatistics.getWeekPrimeHourNum() != null
                        && unitStatistics.getWeekHourNum().compareTo(BigDecimal.ZERO) > 0
                        && unitStatistics.getWeekPrimeHourNum().compareTo(BigDecimal.ZERO) > 0
                        && unitStatistics.getWeekHourNum().compareTo(unitStatistics.getWeekPrimeHourNum()) >= 0) {
                    placeDistribution.setWeekSimpleHourNum(unitStatistics.getWeekHourNum().subtract(unitStatistics.getWeekPrimeHourNum()));  // 周非黄金时段数
                } else {
                    placeDistribution.setWeekSimpleHourNum(BigDecimal.ZERO);
                }
                if (unitStatistics.getWeekSignHourNum() != null
                        && unitStatistics.getWeekSignPrimeHourNum() != null
                        && unitStatistics.getWeekSignHourNum().compareTo(BigDecimal.ZERO) > 0
                        && unitStatistics.getWeekSignPrimeHourNum().compareTo(BigDecimal.ZERO) > 0
                        && unitStatistics.getWeekSignHourNum().compareTo(unitStatistics.getWeekSignPrimeHourNum()) >= 0) {
                    placeDistribution.setWeekSignSimpleHourNum(unitStatistics.getWeekSignHourNum().subtract(unitStatistics.getWeekSignPrimeHourNum()));  // 周非黄金时段数
                } else {
                    placeDistribution.setWeekSignSimpleHourNum(BigDecimal.ZERO);
                }
            } else {
                placeDistribution.setWeekHourNum(BigDecimal.ZERO);
                placeDistribution.setWeekSignHourNum(BigDecimal.ZERO);
                placeDistribution.setWeekPrimeHourNum(BigDecimal.ZERO);
                placeDistribution.setWeekSignPrimeHourNum(BigDecimal.ZERO);
                placeDistribution.setWeekSimpleHourNum(BigDecimal.ZERO);
                placeDistribution.setWeekSignSimpleHourNum(BigDecimal.ZERO);
            }

        }
        return placeDistribution;
    }

    /**
     * 场馆签约状况明细数据取得
     *
     * @param placeId
     * @return
     */
    public PlaceKpiInfo getPlaceSignDetailData(Integer placeId) {
        TbBizPlace bizPlace = placeMapper.selectByPrimaryKey(placeId);
        TbBizPlaceAttach attach = this.getBizPlaceAttach(placeId);
        PlaceKpiInfo placeKpiInfo = new PlaceKpiInfo();
        List<TbBizPlaceUnitStatistics> retStat = vPlaceMapper.getStatisticsByPlaceId(placeId);
        placeKpiInfo.setPlaceName(bizPlace.getName());
        if (attach != null) {
            placeKpiInfo.setLevelName(attach.getPlaceLevel()); // 场馆评级
        }
        if (retStat != null && retStat.size() > 0) {
            TbBizPlaceUnitStatistics stat = retStat.get(0);
            if (stat != null) {
                placeKpiInfo.setPlaceId(placeId);
                placeKpiInfo.setWeekHourTime(stat.getWeekHourNum()); // 周时段数
                placeKpiInfo.setWeekSignHourNum(stat.getWeekSignHourNum());   // 周签约时段数
                placeKpiInfo.setWeekPrimeHourNum(stat.getWeekPrimeHourNum());  // 周黄金时段数
                placeKpiInfo.setWeekSignPrimeHourNum(stat.getWeekSignPrimeHourNum()); // 周已签约黄金时段数

                if (stat.getWeekHourNum().compareTo(BigDecimal.ZERO) > 0) {
                    if (stat.getWeekSignHourNum().compareTo(BigDecimal.ZERO) > 0 && stat.getWeekHourNum().compareTo(stat.getWeekSignHourNum()) >= 0) {
                        // 周未签约时段数
                        placeKpiInfo.setWeekNotSignHourNum(stat.getWeekHourNum().subtract(stat.getWeekSignHourNum()));
                    } else {
                        placeKpiInfo.setWeekNotSignHourNum(stat.getWeekHourNum());
                    }
                    if (stat.getWeekPrimeHourNum().compareTo(BigDecimal.ZERO) > 0 && stat.getWeekHourNum().compareTo(stat.getWeekPrimeHourNum()) >= 0) {
                        // 周非黄金时段数
                        placeKpiInfo.setWeekSimpleHourNum(stat.getWeekHourNum().subtract(stat.getWeekPrimeHourNum()));
                    } else {
                        placeKpiInfo.setWeekSimpleHourNum(stat.getWeekHourNum());
                    }
                    if (stat.getWeekPrimeHourNum().compareTo(BigDecimal.ZERO) > 0
                            && stat.getWeekSignPrimeHourNum().compareTo(BigDecimal.ZERO) > 0
                            && stat.getWeekPrimeHourNum().compareTo(stat.getWeekSignPrimeHourNum()) >= 0) {
                        // 周未签约黄金时间数
                        placeKpiInfo.setWeekNotSignPrimeHourNum(stat.getWeekPrimeHourNum().subtract(stat.getWeekSignPrimeHourNum()));
                    } else {
                        placeKpiInfo.setWeekNotSignPrimeHourNum(stat.getWeekPrimeHourNum());
                    }
                    if (stat.getWeekSignHourNum().compareTo(BigDecimal.ZERO) > 0
                            && stat.getWeekSignPrimeHourNum().compareTo(BigDecimal.ZERO) >= 0
                            && stat.getWeekSignHourNum().compareTo(stat.getWeekSignPrimeHourNum()) >= 0) {
                        // 周签约非黄金时间数
                        placeKpiInfo.setWeekSignSimpleHourNum(stat.getWeekSignHourNum().subtract(stat.getWeekSignPrimeHourNum()));
                    } else {
                        placeKpiInfo.setWeekSignSimpleHourNum(BigDecimal.ZERO);
                    }
                    // 周未签约非黄金时间数
                    placeKpiInfo.setWeekNotSignSimpleHourNum(placeKpiInfo.getWeekNotSignHourNum().subtract(placeKpiInfo.getWeekNotSignPrimeHourNum()));

                } else {
                    placeKpiInfo.setWeekSignSimpleHourNum(BigDecimal.ZERO);
                    placeKpiInfo.setWeekNotSignHourNum(BigDecimal.ZERO);
                    placeKpiInfo.setWeekSimpleHourNum(BigDecimal.ZERO);
                    placeKpiInfo.setWeekNotSignPrimeHourNum(BigDecimal.ZERO);
                    placeKpiInfo.setWeekNotSignSimpleHourNum(BigDecimal.ZERO);
                }
            }
        }
        return placeKpiInfo;
    }

    /**
     * 获取销售地图数据
     *
     * @param cityId
     * @param categoryId
     * @param districtId
     * @return
     */
    public PlaceSaleDistribution getPlaceSaleDistribuctionGroup(Integer cityId, Integer categoryId, Integer districtId) {
        PlaceSaleDistribution result = new PlaceSaleDistribution();
        List<VPlaceSale> placeList = vPlaceMapper.selectPlaceSaleData(cityId, categoryId, districtId);
        Integer unitExistsNum = 0;
        Integer placeExistsNum = 0;
        Map<Integer, VPlaceSale> placeMap = new HashMap<Integer, VPlaceSale>();
        if (null == placeList) {
            return result;
        }
        for (VPlaceSale place : placeList) {
            // 以防存储是检验不严格，查询时不在合理经纬度范围内的排除
            if (place.getLat() <= 0 || place.getLng() <= 0 ||
                    place.getLat() > PlaceConstants.CHINA_MAX_LAT ||
                    place.getLat() < PlaceConstants.CHINA_MIN_LAT ||
                    place.getLng() > PlaceConstants.CHINA_MAX_LNG ||
                    place.getLng() < PlaceConstants.CHINA_MIN_LNG) {
                continue;
            }
            if (!placeMap.containsKey(place.getPlaceId())) {
                // 统一场馆的多片场地，地图上只显示一个坐标
                placeMap.put(place.getPlaceId(), place);
                if (place.getIsSale() != null && place.getIsSale() == 1) {
                    placeExistsNum += 1;  // 场地有销售记录场馆数量
                }

            }
            if (place.getIsSale() != null && Constants.BYTE_ONE == place.getIsSale()) {
                unitExistsNum += 1;  // 片场有销售记录数量
            }

        }
        if (placeMap != null && placeMap.size() > 0) {
            result.setPlaceNum(placeMap.size());
            result.setIsSalePlaceNum(placeExistsNum); // 已存在销售记录的场馆数量
            result.setNotSalePlaceNum(placeMap.size() - placeExistsNum); // 未销售的场馆数量
        } else {
            result.setPlaceNum(0);
            result.setIsSalePlaceNum(0); // 已存在销售记录的场馆数量
            result.setNotSalePlaceNum(0); // 未销售的场馆数量
        }
        if (placeList.size() > 0) {
            result.setPlaceUnitNum(placeList.size());  // 场馆总片数
            result.setIsSaleUnitNum(unitExistsNum); // 已存在销售记录的场地片数
            result.setNotSaleUnitNum(placeList.size() - unitExistsNum); // 未销售的场地片数
        } else {
            result.setPlaceUnitNum(0);
            result.setIsSaleUnitNum(0);
            result.setNotSaleUnitNum(0);
        }
        List<VPlaceSale> filtedResult = new ArrayList<VPlaceSale>(placeMap.values());
        result.setPlaceList(filtedResult);
        return result;
    }

    /**
     * 获取片场信息
     * @param placeId
     * @return
     */
    @Override
    public APIResponse getPlaceUnitData(int placeId,int placeUnitId) {
        TbBizPlaceUnitExample tbBizPlaceUnitExample = new TbBizPlaceUnitExample();
        TbBizPlaceUnitExample.Criteria tbBizPlaceUnitCriteria = tbBizPlaceUnitExample.createCriteria();
        if(placeId > 0){
            tbBizPlaceUnitCriteria.andPlaceIdEqualTo(placeId);
            tbBizPlaceUnitCriteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        }
        if (placeUnitId > 0){
            tbBizPlaceUnitCriteria.andIdEqualTo(placeUnitId);
            tbBizPlaceUnitCriteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        }
        if (placeId <=0 && placeUnitId <= 0){
            return APIResponse.returnFail("placeId或者placeUnitId至少必须填写一个大于0的参数。");
        }

        List<TbBizPlaceUnit> tbBizPlaceUnitList = placeUnitMapper.selectByExample(tbBizPlaceUnitExample);
        if(tbBizPlaceUnitList != null && tbBizPlaceUnitList.size() > 0){
            for (TbBizPlaceUnit tbBizPlaceUnit : tbBizPlaceUnitList){
                tbBizPlaceUnit.setPlaceUnitType(getCommonDataCache(tbBizPlaceUnit.getPlaceUnitType()));
                tbBizPlaceUnit.setPlaceUnitTexture(getCommonDataCache(tbBizPlaceUnit.getPlaceUnitTexture()));
                tbBizPlaceUnit.setLightType(getCommonDataCache(tbBizPlaceUnit.getLightType()));
                tbBizPlaceUnit.setFieldScale(getCommonDataCache(tbBizPlaceUnit.getFieldScale()));
            }
        }

        return APIResponse.returnSuccess(tbBizPlaceUnitList);
    }

    /**
     * 获取场馆详细信息
     * @param placeId
     * @return
     */
    @Override
    public APIResponse getPlaceDetailData(int placeId) {
        PlaceFromDataVo placeFromDataVo = new PlaceFromDataVo();
        TbBizPlaceExample tbBizPlaceExample = new TbBizPlaceExample();
        TbBizPlaceExample.Criteria tbBizPlaceCriteria = tbBizPlaceExample.createCriteria();
        tbBizPlaceCriteria.andIdEqualTo(placeId);
        tbBizPlaceCriteria.andIsDeleteEqualTo(Constants.IS_NO);
        tbBizPlaceCriteria.andSourceIdEqualTo(PlaceConstants.SOURCE_PLACE_BUSINESS);
        List<TbBizPlace> tbBizPlaceList = placeMapper.selectByExample(tbBizPlaceExample);
        if (tbBizPlaceList.isEmpty()){
            return APIResponse.returnFail("不存在该场馆信息！");
        }

        //placeFromDataVo = placeUnitListMapper.selectPlaceDetailMsg(placeId);
        TbBizPlace tbBizPlace = tbBizPlaceList.get(0);
        String city = null;
        String supplier = null;
        if(getCityDataById(tbBizPlace.getCityId()) != null){
            city = getCityDataById(tbBizPlace.getCityId()).getName();
        }
        if(getSupplierDataById(tbBizPlace.getSupplierId()) != null){
            supplier = getSupplierDataById(tbBizPlace.getSupplierId()).getName();
        }
        if (null != tbBizPlace.getDistrictId()){
            TbDistrict district = this.getDistrictById(tbBizPlace.getDistrictId());
            if (null != district && StringUtils.isNotEmpty(district.getName())){
                placeFromDataVo.setDistrictName(district.getName());
            }
        }

        placeFromDataVo.setName(tbBizPlace.getName());
        placeFromDataVo.setCode(tbBizPlace.getCode());
        placeFromDataVo.setAddress(tbBizPlace.getAddress());
        placeFromDataVo.setCityId(tbBizPlace.getCityId());
        placeFromDataVo.setProvinceId(tbBizPlace.getProvinceId());
        placeFromDataVo.setDistrictId(tbBizPlace.getDistrictId());
        placeFromDataVo.setComment(tbBizPlace.getComment());
        placeFromDataVo.setLat(tbBizPlace.getLat());
        placeFromDataVo.setLng(tbBizPlace.getLng());
        placeFromDataVo.setPhone(tbBizPlace.getPhone());
        placeFromDataVo.setContact(tbBizPlace.getContact()); // 运营负责人
        placeFromDataVo.setSupplierId(tbBizPlace.getSupplierId());
        placeFromDataVo.setUid(tbBizPlace.getUid());
        placeFromDataVo.setId(tbBizPlace.getId());
        placeFromDataVo.setIsSign(tbBizPlace.getIsSign());
        placeFromDataVo.setCity(city);
        placeFromDataVo.setSupplier(supplier);
        placeFromDataVo.setBusinessMode(tbBizPlace.getBusinessMode()); // 经营类型


        TbBizPlaceAttachExample tbBizPlaceAttachExample = new TbBizPlaceAttachExample();
        TbBizPlaceAttachExample.Criteria tbBizPlaceAttachCriteria = tbBizPlaceAttachExample.createCriteria();
        tbBizPlaceAttachCriteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceAttach> tbBizPlaceAttachList = tbBizPlaceAttachMapper.selectByExample(tbBizPlaceAttachExample);
        if(tbBizPlaceAttachList.isEmpty()){
            return APIResponse.returnSuccess(placeFromDataVo);
        }
        TbBizPlaceAttach tbBizPlaceAttach = tbBizPlaceAttachList.get(0);

        int placeUnitId = 0;
        APIResponse<List<TbBizPlaceUnit>> apiResponse= getPlaceUnitData(placeId, placeUnitId);
        List<TbBizPlaceUnit> tbBizPlaceUnitList = apiResponse.getData();
        List<TbBizPlaceUnitVo> tbBizPlaceUnitVoList = new ArrayList<TbBizPlaceUnitVo>();

        if (tbBizPlaceAttach != null){
            String manageTypeName = getCommonDataCache(tbBizPlaceAttach.getManageType());
            placeFromDataVo.setManageTypeName(manageTypeName);

            placeFromDataVo.setPlaceId(tbBizPlaceAttach.getPlaceId());
            placeFromDataVo.setIsPrimeLocation(tbBizPlaceAttach.getIsPrimeLocation());
            placeFromDataVo.setIsContainPrimeTime(tbBizPlaceAttach.getIsContainPrimeTime());
            placeFromDataVo.setManageType(tbBizPlaceAttach.getManageType());
            placeFromDataVo.setPlaceLevel(tbBizPlaceAttach.getPlaceLevel());
            placeFromDataVo.setStartBusinessTime(tbBizPlaceAttach.getStartBusinessTime());
            placeFromDataVo.setRemainTime(tbBizPlaceAttach.getRemainTime());
            placeFromDataVo.setIsContainBath(tbBizPlaceAttach.getIsContainBath());
            placeFromDataVo.setIsContainWater(tbBizPlaceAttach.getIsContainWater());
            placeFromDataVo.setIsContainWifi(tbBizPlaceAttach.getIsContainWifi());
            placeFromDataVo.setIsContainHeating(tbBizPlaceAttach.getIsContainHeating());
            placeFromDataVo.setIsContainAc(tbBizPlaceAttach.getIsContainAc());
            placeFromDataVo.setIsContainAdArea(tbBizPlaceAttach.getIsContainAdArea());
            placeFromDataVo.setParkNum(tbBizPlaceAttach.getParkNum());
            placeFromDataVo.setIsParkFree(tbBizPlaceAttach.getIsParkFree());
            placeFromDataVo.setOwnership(tbBizPlaceAttach.getOwnership()); //场馆所有权
            placeFromDataVo.setBusinessHourStart(tbBizPlaceAttach.getBusinessHourStart());
            placeFromDataVo.setBusinessHourEnd(tbBizPlaceAttach.getBusinessHourEnd());
            placeFromDataVo.setHolidayBusinessHourStart(tbBizPlaceAttach.getHolidayBusinessHourStart());
            placeFromDataVo.setHolidayBusinessHourEnd(tbBizPlaceAttach.getHolidayBusinessHourEnd());
            placeFromDataVo.setIsVip(tbBizPlaceAttach.getIsVip());
            placeFromDataVo.setIsVipHouse(tbBizPlaceAttach.getIsVipHouse());
            placeFromDataVo.setIsTrain(tbBizPlaceAttach.getIsTrain());
            placeFromDataVo.setIsLockerRoom(tbBizPlaceAttach.getIsLockerRoom());
            placeFromDataVo.setPlaceGoods(tbBizPlaceAttach.getPlaceGoods());
            placeFromDataVo.setBookingConsultPhone(tbBizPlaceAttach.getBookingConsultPhone()); // 订场咨询电话

            String trafficInfoString = tbBizPlaceAttach.getTrafficInfo();//设置交通信息列表
            List<RespBizPlaceTrafficInfo> trafficInfoList = new ArrayList<>();
            if(!org.springframework.util.StringUtils.isEmpty(trafficInfoString)){
                String[] trafficInfos = trafficInfoString.split("\\|");
                for (String trafficInfo : trafficInfos) {
                    String[] trafficInfoStr = trafficInfo.split(":");
                    RespBizPlaceTrafficInfo respBizPlaceTrafficInfo = new RespBizPlaceTrafficInfo();
                    respBizPlaceTrafficInfo.setType(trafficInfoStr[0]);
                    respBizPlaceTrafficInfo.setDescribe(trafficInfoStr[1]);
                    trafficInfoList.add(respBizPlaceTrafficInfo);
                }
                placeFromDataVo.setTrafficInfoList(trafficInfoList);
            }

        }


        TbPlaceImageExample tbPlaceImageExample = new TbPlaceImageExample();
        TbPlaceImageExample.Criteria tbPlaceImageCriteria = tbPlaceImageExample.createCriteria();
        tbPlaceImageCriteria.andTopicIdEqualTo(placeId);
        tbPlaceImageExample.setOrderByClause("id");
        // 获取场馆附属媒介
        List<TbPlaceImage> tbPlaceAttachList = tbPlaceImageMapper.selectUrlByExample(tbPlaceImageExample);
        List<TbPlaceImage> imageList = new ArrayList<TbPlaceImage>();
        for (TbPlaceImage placeAttach : tbPlaceAttachList){
            if (PlaceConstants.PLACE_ATTACH_IMAGE == placeAttach.getContentType()){
                imageList.add(placeAttach);  // 图片
            } else if (PlaceConstants.PLACE_ATTACH_VIDEO == placeAttach.getContentType()){
                placeFromDataVo.setVideoUrl(placeAttach.getUrl()); // 视频
            }
        }
        placeFromDataVo.setPlace_attach_list(imageList);

        TbBizPlaceCategoryExample tbBizPlaceCategoryExample = new TbBizPlaceCategoryExample();
        TbBizPlaceCategoryExample.Criteria tbBizPlaceCategoryCriteria = tbBizPlaceCategoryExample.createCriteria();
        tbBizPlaceCategoryCriteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceCategory> tbBizPlaceCategoryList  = tbBizPlaceCategoryMapper.selectByExample(tbBizPlaceCategoryExample);
        if(tbBizPlaceCategoryList != null && tbBizPlaceCategoryList.size() > 0){
            List<Integer> placeCategoryList = new ArrayList<Integer>();
            for (TbBizPlaceCategory tbBizPlaceCategory : tbBizPlaceCategoryList) {
                placeCategoryList.add(tbBizPlaceCategory.getCategoryId());
            }
            placeFromDataVo.setPlaceCategoryList(placeCategoryList);
        }


        if(tbBizPlaceUnitList != null && tbBizPlaceUnitList.size() > 0){
            for (TbBizPlaceUnit tbBizPlaceUnit : tbBizPlaceUnitList){
                TbBizPlaceUnitVo tbBizPlaceUnitVo = new TbBizPlaceUnitVo();
                tbBizPlaceUnitVo.setLightType(tbBizPlaceUnit.getLightType());
                tbBizPlaceUnitVo.setPlaceUnitType(tbBizPlaceUnit.getPlaceUnitType());
                tbBizPlaceUnitVo.setPlaceUnitTexture(tbBizPlaceUnit.getPlaceUnitTexture());
                tbBizPlaceUnitVo.setFieldScale(tbBizPlaceUnit.getFieldScale());
                tbBizPlaceUnitVo.setCategoryId(tbBizPlaceUnit.getCategoryId());
                tbBizPlaceUnitVo.setName(tbBizPlaceUnit.getName());
                tbBizPlaceUnitVo.setComment(tbBizPlaceUnit.getComment());
                tbBizPlaceUnitVo.setPlaceId(tbBizPlaceUnit.getPlaceId());
                tbBizPlaceUnitVo.setId(tbBizPlaceUnit.getId());
                tbBizPlaceUnitVo.setIsSign(tbBizPlaceUnit.getIsSign());

                TbBizPlaceUnitTimeExample tbBizPlaceUnitTimeExample = new TbBizPlaceUnitTimeExample();
                TbBizPlaceUnitTimeExample.Criteria criteria = tbBizPlaceUnitTimeExample.createCriteria();
                criteria.andPlaceUnitIdEqualTo(tbBizPlaceUnit.getId());
                List<TbBizPlaceUnitTime> tbBizPlaceUnitTimes = placeUnitTimeMapper.selectByExample(tbBizPlaceUnitTimeExample);
                tbBizPlaceUnitVo.setPlace_unit_time_list(tbBizPlaceUnitTimes);


                tbBizPlaceUnitVoList.add(tbBizPlaceUnitVo);
            }
        }
        placeFromDataVo.setPlace_unit_list(tbBizPlaceUnitVoList);

        return APIResponse.returnSuccess(placeFromDataVo);

    }

    /**
     * 获取省信息
     * @return
     */
    @Override
    public APIResponse getProvinceData() {
        TbProvinceExample tbProvinceExample = new TbProvinceExample();
        TbProvinceExample.Criteria tbProvinceCriteria  = tbProvinceExample.createCriteria();
        tbProvinceCriteria.andIsEnableEqualTo(1);
        tbProvinceExample.setOrderByClause("priority");
        List<TbProvince> list = tbProvinceMapper.selectNameByExample(tbProvinceExample);
        return APIResponse.returnSuccess(list);
    }

    /**
     * 获取省下的城市信息
     * @param provinceId
     * @param isEnabled
     * @return
     */
    @Override
    public APIResponse getCityData(Integer provinceId, boolean isEnabled) {
        try {
            TbCityExample tbCityExample = new TbCityExample();
            TbCityExample.Criteria tbCityCriteria = tbCityExample.createCriteria();
            if (provinceId != null && provinceId > 0){
                tbCityCriteria.andProvinceIdEqualTo(provinceId);
            }
            if (isEnabled){
                tbCityCriteria.andIsEnableEqualTo(1);
            }
            tbCityExample.setOrderByClause("priority");
            List<TbCity> list = tbCityMapper.selectNameByExample(tbCityExample);
            return APIResponse.returnSuccess(list);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return APIResponse.returnFail(ApiResponseEnum.RESOURCE_NOT_FOUND);

    }

    @Override
    public APIResponse getCityData(Integer cityId) {
        TbCity city = getCityDataById(cityId);
        return APIResponse.returnSuccess(city);
    }

    public TbCity getCityDataById(Integer cityId) {
        TbCityExample tbCityExample = new TbCityExample();
        TbCityExample.Criteria tbCityCriteria = tbCityExample.createCriteria();
        tbCityCriteria.andIdEqualTo(cityId);
        List<TbCity> list = tbCityMapper.selectNameByExample(tbCityExample);
        if (list!=null&&list.size()!=0){
            return list.get(0);
        }else{
            return null;
        }
    }

    /**
     * 根据提供商id查询提供商信息
     * @param supplierId
     * @return
     */
    public TbSupplier getSupplierDataById(Integer supplierId) {
        TbSupplier supplier = tbSupplierMapper.selectByPrimaryKey(supplierId);
        return supplier;
    }

    /**
     * 根据区域Id查询区域信息
     * @param districtId
     * @return
     */
    public TbDistrict getDistrictById(Integer districtId){
        TbDistrict district = tbDistrictMapper.selectByPrimaryKey(districtId);
        return district;
    }


    /**
     * 录入场地信息（旧）
     * 包含录入场地、维护营业时间、黄金时间段设置等
     * @param placeId
     * @param placeUnitVoList
     * @return
     */
    @Override
    @Transactional
    public APIResponse importPlaceUnitData(Integer placeId, List<TbBizPlaceUnitVo> placeUnitVoList) {
        for(TbBizPlaceUnitVo tbBizPlaceUnitVo : placeUnitVoList){
            TbBizPlaceUnitExample tbBizPlaceUnitExample = new TbBizPlaceUnitExample();
            TbBizPlaceUnitExample.Criteria tbBizPlaceUnitCriteria = tbBizPlaceUnitExample.createCriteria();
            tbBizPlaceUnitCriteria.andNameEqualTo(tbBizPlaceUnitVo.getName());
            tbBizPlaceUnitCriteria.andPlaceIdEqualTo(placeId);
            tbBizPlaceUnitCriteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
            tbBizPlaceUnitCriteria.andCategoryIdEqualTo(tbBizPlaceUnitVo.getCategoryId());
            List<TbBizPlaceUnit> tbBizPlaceUnitList = placeUnitMapper.selectByExample(tbBizPlaceUnitExample);
            if(tbBizPlaceUnitList != null && tbBizPlaceUnitList.size() > 0){
                return APIResponse.returnFail( "场地名称：" + tbBizPlaceUnitVo.getName() + "已经存在！");
            }

        }

        TbBizPlaceExample tbBizPlaceExample = new TbBizPlaceExample();
        TbBizPlaceExample.Criteria tbBizPlaceCriteria = tbBizPlaceExample.createCriteria();
        tbBizPlaceCriteria.andIdEqualTo(placeId);
        tbBizPlaceCriteria.andIsDeleteEqualTo(Constants.IS_NO);
        List<TbBizPlace> tbBizPlaceList = placeMapper.selectByExample(tbBizPlaceExample);
        if (tbBizPlaceList.isEmpty()){
            return APIResponse.returnFail("不存在该场馆信息！");
        }
        TbBizPlace tbBizPlace = tbBizPlaceList.get(0);
        String placeName = tbBizPlace.getName();

        Boolean isPrimeTime = false;
        for (TbBizPlaceUnitVo tbBizPlaceUnitVo : placeUnitVoList){
            TbBizPlaceUnit tbBizPlaceUnit = new TbBizPlaceUnit();
            tbBizPlaceUnit.setName(tbBizPlaceUnitVo.getName());
            tbBizPlaceUnit.setPlaceId(placeId);
            tbBizPlaceUnit.setCategoryId(tbBizPlaceUnitVo.getCategoryId());
            tbBizPlaceUnit.setExtendName(placeName + "_" + tbBizPlaceUnit.getName() + "_" + getCommonDataCache("cagetory"+tbBizPlaceUnit.getCategoryId().toString())+"场");
            Short sh = 0;
            tbBizPlaceUnit.setPriority(sh);
            tbBizPlaceUnit.setComment(tbBizPlaceUnitVo.getComment());
            tbBizPlaceUnit.setFieldScale(tbBizPlaceUnitVo.getFieldScale());
            tbBizPlaceUnit.setLightType(tbBizPlaceUnitVo.getLightType());
            tbBizPlaceUnit.setPlaceUnitTexture(tbBizPlaceUnitVo.getPlaceUnitTexture());
            tbBizPlaceUnit.setPlaceUnitType(tbBizPlaceUnitVo.getPlaceUnitType());
            tbBizPlaceUnit.setIsDelete(Constants.IS_DELETE_FALSE);
            tbBizPlaceUnit.setIsSign(Constants.BYTE_ZERO);

            tbBizPlaceUnit.setIsCombine(Constants.BYTE_ZERO);

            placeUnitMapper.insertSelective(tbBizPlaceUnit);//插入片场表

            //插入营业时间
            List<TbBizPlaceUnitTime> tbBizPlaceUnitTimes = tbBizPlaceUnitVo.getPlace_unit_time_list();
            for(TbBizPlaceUnitTime tbBizPlaceUnitTime:tbBizPlaceUnitTimes){
                if(tbBizPlaceUnitTime.getIsPrimeTime() == 1){
                    isPrimeTime = true;
                }
                String time_length = "00:00:00";
                try {
                    time_length = TimeUtils.subtractTime(tbBizPlaceUnitTime.getStartTime(), tbBizPlaceUnitTime.getEndTime());
                }
                catch (ParseException e){
                    e.printStackTrace();
                }
                tbBizPlaceUnitTime.setTimeLength(TimeUtils.timeToHour(time_length));
                tbBizPlaceUnitTime.setPlaceUnitId(tbBizPlaceUnit.getId());
                tbBizPlaceUnitTime.setPlaceId(placeId);
                placeUnitTimeMapper.insert(tbBizPlaceUnitTime);
            }

            /*TbBizPlaceUnitStatistics tbBizPlaceUnitStatistics = getPlaceUnitStatisticsBean(tbBizPlaceUnitTimes);
            tbBizPlaceUnitStatistics.setIsSign(Constants.BYTE_ZERO);
            tbBizPlaceUnitStatistics.setWeekSignHourNum(BigDecimal.ZERO);
            tbBizPlaceUnitStatistics.setWeekSignPrimeHourNum(BigDecimal.ZERO);

            unitStatisticsMapper.insert(tbBizPlaceUnitStatistics); //插入片场黄金时间统计表*/
        }
        //更新场馆黄金时间属性
        if(isPrimeTime){
            TbBizPlaceAttach tbBizPlaceAttach = new TbBizPlaceAttach();
            tbBizPlaceAttach.setIsContainPrimeTime((byte) 1);
            TbBizPlaceAttachExample tbBizPlaceAttachExample = new TbBizPlaceAttachExample();
            TbBizPlaceAttachExample.Criteria tbBizPlaceAttachCriteria = tbBizPlaceAttachExample.createCriteria();
            tbBizPlaceAttachCriteria.andPlaceIdEqualTo(placeId);
            tbBizPlaceAttachMapper.updateByExampleSelective(tbBizPlaceAttach,tbBizPlaceAttachExample);
        }
        return APIResponse.returnSuccess("录入完成");
    }


    /**
     * 保存场地信息
     * @param placeId
     * @param placeUnitVoList
     * @return
     */
    @Transactional
    public APIResponse savePlaceUnitData(Integer placeId, List<TbBizPlaceUnitVo> placeUnitVoList) {
        for(TbBizPlaceUnitVo tbBizPlaceUnitVo : placeUnitVoList){
            TbBizPlaceUnitExample tbBizPlaceUnitExample = new TbBizPlaceUnitExample();
            TbBizPlaceUnitExample.Criteria tbBizPlaceUnitCriteria = tbBizPlaceUnitExample.createCriteria();
            tbBizPlaceUnitCriteria.andNameEqualTo(tbBizPlaceUnitVo.getName());
            tbBizPlaceUnitCriteria.andPlaceIdEqualTo(placeId);
            tbBizPlaceUnitCriteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
            tbBizPlaceUnitCriteria.andCategoryIdEqualTo(tbBizPlaceUnitVo.getCategoryId());
            List<TbBizPlaceUnit> tbBizPlaceUnitList = placeUnitMapper.selectByExample(tbBizPlaceUnitExample);
            if(tbBizPlaceUnitList != null && tbBizPlaceUnitList.size() > 0){
                return APIResponse.returnFail( "场地名称：" + tbBizPlaceUnitVo.getName() + "已经存在！");
            }

        }

        TbBizPlaceExample tbBizPlaceExample = new TbBizPlaceExample();
        TbBizPlaceExample.Criteria tbBizPlaceCriteria = tbBizPlaceExample.createCriteria();
        tbBizPlaceCriteria.andIdEqualTo(placeId);
        tbBizPlaceCriteria.andIsDeleteEqualTo(Constants.IS_NO);
        List<TbBizPlace> tbBizPlaceList = placeMapper.selectByExample(tbBizPlaceExample);
        if (tbBizPlaceList.isEmpty()){
            return APIResponse.returnFail("不存在该场馆信息！");
        }
        TbBizPlace tbBizPlace = tbBizPlaceList.get(0);
        String placeName = tbBizPlace.getName();
        // 插入片场信息
        for (TbBizPlaceUnitVo tbBizPlaceUnitVo : placeUnitVoList){
            TbBizPlaceUnit tbBizPlaceUnit = new TbBizPlaceUnit();
            tbBizPlaceUnit.setName(tbBizPlaceUnitVo.getName());
            tbBizPlaceUnit.setPlaceId(placeId);
            tbBizPlaceUnit.setCategoryId(tbBizPlaceUnitVo.getCategoryId());
            tbBizPlaceUnit.setExtendName(placeName + "_" + tbBizPlaceUnit.getName() + "_" + getCommonDataCache("cagetory"+tbBizPlaceUnit.getCategoryId().toString())+"场");
            Short sh = 0;
            tbBizPlaceUnit.setPriority(sh);
            tbBizPlaceUnit.setComment(tbBizPlaceUnitVo.getComment());
            tbBizPlaceUnit.setFieldScale(tbBizPlaceUnitVo.getFieldScale());
            tbBizPlaceUnit.setLightType(tbBizPlaceUnitVo.getLightType());
            tbBizPlaceUnit.setPlaceUnitTexture(tbBizPlaceUnitVo.getPlaceUnitTexture());
            tbBizPlaceUnit.setPlaceUnitType(tbBizPlaceUnitVo.getPlaceUnitType());
            tbBizPlaceUnit.setIsDelete(Constants.IS_DELETE_FALSE);
            tbBizPlaceUnit.setIsSign(Constants.BYTE_ZERO);
            tbBizPlaceUnit.setIsCombine(Constants.BYTE_ZERO);
            placeUnitMapper.insertSelective(tbBizPlaceUnit);//插入片场表
        }
        return APIResponse.returnSuccess("录入完成");
    }

    @Override
    @Transactional
    public APIResponse updatePlaceData(PlaceFromDataVo placeFromDataVo) {
        List<TbPlaceImage> tbPlaceImageList = placeFromDataVo.getPlace_attach_list();
        TbBizPlaceExample tbBizPlaceExample = new TbBizPlaceExample();
        TbBizPlaceExample.Criteria tbBizPlaceCriteria = tbBizPlaceExample.createCriteria();
        tbBizPlaceCriteria.andNameEqualTo(placeFromDataVo.getName());
        tbBizPlaceCriteria.andIsDeleteEqualTo(Constants.IS_NO);
        tbBizPlaceCriteria.andIdNotEqualTo(placeFromDataVo.getId());
        List<TbBizPlace> tbBizPlaceList =  placeMapper.selectByExample(tbBizPlaceExample);
        if(tbBizPlaceList != null && tbBizPlaceList.size() > 0){
            return APIResponse.returnFail("场馆名称已经存在!");
        }

        TbBizPlace tbBizPlace = new TbBizPlace();
        tbBizPlace.setId(placeFromDataVo.getId());
        tbBizPlace.setName(placeFromDataVo.getName());
        tbBizPlace.setCityId(placeFromDataVo.getCityId());
        tbBizPlace.setAddress(placeFromDataVo.getAddress());
        tbBizPlace.setComment(placeFromDataVo.getComment());
        tbBizPlace.setDistrictId(placeFromDataVo.getDistrictId());
        tbBizPlace.setProvinceId(placeFromDataVo.getProvinceId());
        tbBizPlace.setContact(placeFromDataVo.getContact());
        tbBizPlace.setLat(placeFromDataVo.getLat());
        tbBizPlace.setLng(placeFromDataVo.getLng());
        tbBizPlace.setSupplierId(placeFromDataVo.getSupplierId());
        tbBizPlace.setPhone(placeFromDataVo.getPhone());
        tbBizPlace.setBusinessMode(placeFromDataVo.getBusinessMode());

        if (null != placeFromDataVo.getCode()){
            tbBizPlace.setCode(placeFromDataVo.getCode());
        }
        if(tbPlaceImageList != null && tbPlaceImageList.size() > 0){
            tbBizPlace.setBizPlaceUrl(tbPlaceImageList.get(0).getUrl());
        }
        placeMapper.updateByPrimaryKeySelective(tbBizPlace);



        TbBizPlaceAttach tbBizPlaceAttach = new TbBizPlaceAttach();
        tbBizPlaceAttach.setPlaceId(placeFromDataVo.getId());
        tbBizPlaceAttach.setIsPrimeLocation(placeFromDataVo.getIsPrimeLocation());
        tbBizPlaceAttach.setIsContainPrimeTime(placeFromDataVo.getIsContainPrimeTime());
        tbBizPlaceAttach.setManageType(placeFromDataVo.getManageType());
        tbBizPlaceAttach.setPlaceLevel(placeFromDataVo.getPlaceLevel());
        tbBizPlaceAttach.setStartBusinessTime(placeFromDataVo.getStartBusinessTime());
        tbBizPlaceAttach.setRemainTime(placeFromDataVo.getRemainTime());
        tbBizPlaceAttach.setIsContainBath(placeFromDataVo.getIsContainBath());
        tbBizPlaceAttach.setIsContainWater(placeFromDataVo.getIsContainWater());
        tbBizPlaceAttach.setIsContainWifi(placeFromDataVo.getIsContainWifi());
        tbBizPlaceAttach.setIsContainHeating(placeFromDataVo.getIsContainHeating());
        tbBizPlaceAttach.setIsContainAc(placeFromDataVo.getIsContainAc());
        tbBizPlaceAttach.setIsContainAdArea(placeFromDataVo.getIsContainAdArea());
        tbBizPlaceAttach.setParkNum(placeFromDataVo.getParkNum());
        tbBizPlaceAttach.setIsParkFree(placeFromDataVo.getIsParkFree());
        //tbBizPlaceAttach.setOwnership(placeFromDataVo.getOwnership()); //场馆所有权
        tbBizPlaceAttach.setBusinessHourStart(placeFromDataVo.getBusinessHourStart());
        tbBizPlaceAttach.setBusinessHourEnd(placeFromDataVo.getBusinessHourEnd());
        tbBizPlaceAttach.setHolidayBusinessHourStart(placeFromDataVo.getHolidayBusinessHourStart());
        tbBizPlaceAttach.setHolidayBusinessHourEnd(placeFromDataVo.getHolidayBusinessHourEnd());

        tbBizPlaceAttach.setIsVip(placeFromDataVo.getIsVip());
        tbBizPlaceAttach.setIsVipHouse(placeFromDataVo.getIsVipHouse());
        tbBizPlaceAttach.setIsTrain(placeFromDataVo.getIsTrain());
        tbBizPlaceAttach.setIsLockerRoom(placeFromDataVo.getIsLockerRoom());
        tbBizPlaceAttach.setPlaceGoods(placeFromDataVo.getPlaceGoods());
        tbBizPlaceAttach.setBookingConsultPhone(placeFromDataVo.getBookingConsultPhone()); // 订场咨询电话
        if(CollectionUtils.isNotEmpty(placeFromDataVo.getTrafficInfoList())){
            List<RespBizPlaceTrafficInfo> trafficInfoList = placeFromDataVo.getTrafficInfoList();
            StringBuffer trafficInfoBuffer = new StringBuffer();
            for (RespBizPlaceTrafficInfo respBizPlaceTrafficInfo : trafficInfoList) {
                trafficInfoBuffer.append(respBizPlaceTrafficInfo.getType());
                trafficInfoBuffer.append(":");
                trafficInfoBuffer.append(respBizPlaceTrafficInfo.getDescribe());
                trafficInfoBuffer.append("|");
            }
            if (trafficInfoBuffer.length() > 1){
                tbBizPlaceAttach.setTrafficInfo(trafficInfoBuffer.substring(0,trafficInfoBuffer.length() - 1));
            }
        }

        placeAttachMapper.updateByPlaceIdSelective(tbBizPlaceAttach);
        return APIResponse.returnSuccess();
    }

    public void updatePlaceImageAndVideo(PlaceFromDataVo placeFromDataVo, Integer placeId) {

        // 图片和视频的处理
        // 前端返回的图片集合
        List<TbPlaceImage> placeImageList = placeFromDataVo.getPlace_attach_list();
        if (null == placeImageList || placeImageList.size() == 0){
            return;
        }
        Set<String> selectedPicSet = new HashSet<String>();
        if (placeImageList != null && placeImageList.size() > 0){
            for (TbPlaceImage tbPlaceImage : placeImageList) {
                selectedPicSet.add(tbPlaceImage.getUrl());
            }
        }
        String videoUrl = placeFromDataVo.getVideoUrl();
        // 修改前已经存在的图片
        Set<String> alreadyExistsPicUrlSet = new HashSet<String>();
        TbPlaceImageExample tbPlaceImageExample = new TbPlaceImageExample();
        TbPlaceImageExample.Criteria tbPlaceImageCriteria = tbPlaceImageExample.createCriteria();
        tbPlaceImageCriteria.andTopicIdEqualTo(placeFromDataVo.getId());
        //tbPlaceImageCriteria.andContentTypeEqualTo(PlaceConstants.PLACE_ATTACH_IMAGE); // 图片
        List<TbPlaceImage> tbPlaceImageList = tbPlaceImageMapper.selectByExample(tbPlaceImageExample);
        String alreadyExistsVideoUrl = null;

        for (TbPlaceImage tbPlaceImage : tbPlaceImageList){
            // 删除以前上传并关联场馆，这次要删除的图片
            if (PlaceConstants.PLACE_ATTACH_IMAGE == tbPlaceImage.getContentType()){
                // 图片
                alreadyExistsPicUrlSet.add(tbPlaceImage.getUrl());
                if (!selectedPicSet.contains(tbPlaceImage.getUrl())){
                    // 原来已经上传了，现在要取消的部分图片
                    tbPlaceImageMapper.deleteByPrimaryKey(tbPlaceImage.getId());
                }
            } else if (PlaceConstants.PLACE_ATTACH_VIDEO == tbPlaceImage.getContentType()){
                // 当前已保存的视频
                alreadyExistsVideoUrl = tbPlaceImage.getUrl();
                if (StringUtils.isNotEmpty(videoUrl) && !videoUrl.equals(alreadyExistsVideoUrl)){
                    // 视频有变更 删除原来的视频
                    tbPlaceImageMapper.deleteByPrimaryKey(tbPlaceImage.getId());
                }
            }
        }

        if (StringUtils.isNotEmpty(videoUrl)){
            if (null == alreadyExistsVideoUrl || (StringUtils.isNotEmpty(alreadyExistsVideoUrl) && !videoUrl.equals(alreadyExistsVideoUrl))){
                 // 新增视频
                TbPlaceImage placeVideo = new TbPlaceImage();
                placeVideo.setContentType(PlaceConstants.PLACE_ATTACH_VIDEO);
                placeVideo.setTopicId(placeId);
                placeVideo.setTitle(placeFromDataVo.getName() + "视频");
                placeVideo.setUrl(videoUrl);
                placeVideo.setSize(0);
                tbPlaceImageMapper.insert(placeVideo);
            }
        }

        // 新增部分图片
        for (String url : selectedPicSet){
            // 不存在于数据库的部分图片
            if (!alreadyExistsPicUrlSet.contains(url)){
                TbPlaceImage placeImage = new TbPlaceImage();
                placeImage.setContentType(PlaceConstants.PLACE_ATTACH_IMAGE);
                placeImage.setTopicId(placeId);
                placeImage.setTitle(placeFromDataVo.getName() + "图片");
                placeImage.setUrl(url);
                placeImage.setSize(0);
                tbPlaceImageMapper.insert(placeImage);
            }
        }
    }

    /**
     * 判断是否存在指定场馆指定日期的销售计划
     * @param placeId
     * @param appointedDate
     * @return
     */
    @Override
    public boolean existsSalePlan(Integer placeId, Date appointedDate) {
        TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        criteria.andDateEqualTo(appointedDate);
        int count = placeUnitSalePlanMapper.countByExample(example);
        if (count > 0){
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查指定日期销售计划个数
     * @param placeId
     * @param appointedDate
     * @param salePlanTemplateNum
     * @return
     */
    public boolean checkSalePlanNum(Integer placeId, Date appointedDate, int salePlanTemplateNum){
        TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        criteria.andDateEqualTo(appointedDate);
        int count = placeUnitSalePlanMapper.countByExample(example);
        if (count == salePlanTemplateNum){
            return true;
        } else {
            return false;
        }
    }

    /**
     * 查询指定场馆指定日期销售计划个数
     * @param placeId
     * @param appointedDate
     * @return
     */
    public int countSalePlanNum(Integer placeId, Date appointedDate){
        TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        criteria.andDateEqualTo(appointedDate);
        criteria.andIsEffectiveEqualTo(Constants.YES);
        return placeUnitSalePlanMapper.countByExample(example);
    }

    /**
     * 根据场馆Id和类目ID获取场地可销售列表，用于定价
     *
     * @param placeId
     * @param categoryId
     * @return
     */
    public List<PlaceUnitSalePlan> getPlaceUnitSalePlan(Integer placeId, Byte categoryId, int interValTime) {
        List<PlaceUnitSalePlan> result = new ArrayList<PlaceUnitSalePlan>();
        TbBizPlaceUnitExample example = new TbBizPlaceUnitExample();
        TbBizPlaceUnitExample.Criteria criterial = example.createCriteria();
        if (placeId != null) {
            criterial.andPlaceIdEqualTo(placeId);
        }
        if (categoryId != null) {
            criterial.andCategoryIdEqualTo(categoryId);
        }
        criterial.andIsSignEqualTo(Constants.BYTE_ONE);
        // 获取场馆下已签约场地列表
        List<TbBizPlaceUnit> placeUnitList = placeUnitMapper.selectByExample(example);
        if (null == placeUnitList || placeUnitList.size() == 0) {
            return result;
        }
        // 如果存在销售计划 从销售计划表查询
        List<PlaceUnitSalePlan> placeUnitSalePlanList = this.getPlaceSalePlanFromDB(placeId, categoryId, UNIT_TYPE_BASE);

        // 查询所有已定价和未定价场地信息
        List<PlaceUnitSalePlan> allUnitSalePlanList = this.getAllUnitSalePlanList(placeId, placeUnitList, interValTime);
        /*if (null != placeUnitSalePlanList && placeUnitSalePlanList.size() > 0) {
            List<PlaceUnitSalePlan> subTractList = (List<PlaceUnitSalePlan>) CollectionUtils.subtract(allUnitSalePlanList, placeUnitSalePlanList);
            // 已经定价的销售计划 uniton 从未定价（比如刚刚签约的场地）的销售计划
            result = (List<PlaceUnitSalePlan>) CollectionUtils.union(placeUnitSalePlanList, subTractList);
            return result;
        } else {
            return allUnitSalePlanList;
        }*/
        for (PlaceUnitSalePlan allPlaceUnitSalePlan : allUnitSalePlanList){
            for (PlaceUnitSalePlan dbPlaceUnitSalePlan : placeUnitSalePlanList){
                if (allPlaceUnitSalePlan.getStartTime().equals(dbPlaceUnitSalePlan.getStartTime())
                        && allPlaceUnitSalePlan.getEndTime().equals(dbPlaceUnitSalePlan.getEndTime())
                        && allPlaceUnitSalePlan.getTimeType().equals(dbPlaceUnitSalePlan.getTimeType())
                        && allPlaceUnitSalePlan.getPlaceUnitId().equals(dbPlaceUnitSalePlan.getPlaceUnitId())
                        && allPlaceUnitSalePlan.getPlaceId().equals(dbPlaceUnitSalePlan.getPlaceId())){
                    try{
                        BeanUtils.copyProperties(allPlaceUnitSalePlan,dbPlaceUnitSalePlan);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
        return allUnitSalePlanList;
    }

    /**
     * 根据场馆Id和类目ID获取组合场地可销售列表，用于定价
     *
     * @param placeId
     * @param categoryId
     * @return
     */
    public List<PlaceUnitSalePlan> getPlaceCombinedUnitSalePlan(Integer placeId, Byte categoryId, int intervalTime) {
        List<PlaceUnitSalePlan> result = new ArrayList<PlaceUnitSalePlan>();

        // 查询所有的组合场地
        TbBizPlaceUnitCombineExample example = new TbBizPlaceUnitCombineExample();
        TbBizPlaceUnitCombineExample.Criteria criterial = example.createCriteria();
        if (placeId != null) {
            criterial.andPlaceIdEqualTo(placeId);
        }
        if (categoryId != null) {
            criterial.andCategoryIdEqualTo(categoryId);
        }
        criterial.andIsDeleteEqualTo((byte) 0);
        List<TbBizPlaceUnitCombine> placeUnitList = pucMapper.selectByExample(example);
        if (null == placeUnitList || placeUnitList.size() <= 0) {
            return result;
        }

        // 如果存在销售计划 从销售计划表查询
        List<PlaceUnitSalePlan> placeUnitSalePlanList = this.getPlaceSalePlanFromDB(placeId, categoryId, UNIT_TYPE_COMBINE);
        // 查询所有已定价和未定价场地信息
        List<PlaceUnitSalePlan> allUnitSalePlanList = this.getAllCombineUnitSalePlanList(placeId, placeUnitList, intervalTime);
        if (null != placeUnitSalePlanList && placeUnitSalePlanList.size() > 0) {
            List<PlaceUnitSalePlan> subTractList = (List<PlaceUnitSalePlan>) CollectionUtils.subtract(allUnitSalePlanList, placeUnitSalePlanList);
            // 已经定价的销售计划 uniton 从未定价（比如刚刚签约的场地）的销售计划
            result = (List<PlaceUnitSalePlan>) CollectionUtils.union(placeUnitSalePlanList, subTractList);
            return result;
        } else {
            return allUnitSalePlanList;
        }
    }

    /**
     * 根据营业时间和签约状况组合组合场地的可销售计划列表
     *
     * @param placeId
     * @param placeUnitList
     * @return
     */
    public List<PlaceUnitSalePlan> getAllCombineUnitSalePlanList(Integer placeId, List<TbBizPlaceUnitCombine> placeUnitList, int section) {
        List<PlaceUnitSalePlan> result = new ArrayList<PlaceUnitSalePlan>();

        for (TbBizPlaceUnitCombine puc : placeUnitList) {
            List<Integer> baseUnitIds = PlaceUtil.splitIds(puc.getBaseUnits());
            if (baseUnitIds == null || baseUnitIds.size() <= 0) {
                continue;
            }
            // 查询所有的基本单位场地信息
            TbBizPlaceUnitExample example = new TbBizPlaceUnitExample();
            TbBizPlaceUnitExample.Criteria criterial = example.createCriteria();
            if (placeId != null) {
                criterial.andPlaceIdEqualTo(placeId);
            }
            criterial.andIdIn(baseUnitIds);
            List<TbBizPlaceUnit> baseUnitList = placeUnitMapper.selectByExample(example);
            if (null == baseUnitList || baseUnitList.size() == 0) {
                continue;
            }

            List<PlaceUnitSalePlan> subUnitSPs = getAllUnitSalePlanList(placeId, baseUnitList, section);
            if (subUnitSPs != null && subUnitSPs.size() > 0) {
                Map<String, List<PlaceUnitSalePlan>> timeSlotMap = new HashMap<>();
                for (PlaceUnitSalePlan salePlan: subUnitSPs) {
                    String key = String.format("%s_%s_%s", salePlan.getTimeType(), salePlan.getStartTime(), salePlan.getEndTime());
                    List<PlaceUnitSalePlan> slotList = timeSlotMap.get(key);
                    if (slotList == null) {
                        slotList = new LinkedList<>();
                        timeSlotMap.put(key, slotList);
                    }
                    slotList.add(salePlan);
                }

                List<PlaceUnitSalePlan> thisCUSalePlans = new ArrayList<PlaceUnitSalePlan>();
                for (Map.Entry<String, List<PlaceUnitSalePlan>> entry : timeSlotMap.entrySet()) {
                    String key = entry.getKey();
                    List<PlaceUnitSalePlan> subSalePlans = entry.getValue();
                    // 同一时段所有子场地都有效的,组合场才能定价
                    if (subSalePlans != null && subSalePlans.size() == baseUnitIds.size()) {
                        String[] parts = key.split("_");

                        PlaceUnitSalePlan placeUnitSalePlan = new PlaceUnitSalePlan();
                        placeUnitSalePlan.setStartTime(parts[1]);
                        placeUnitSalePlan.setEndTime(parts[2]);
                        placeUnitSalePlan.setTimeType(parts[0]);
                        placeUnitSalePlan.setPlaceUnitId(puc.getId());
                        placeUnitSalePlan.setPlaceUnitName(puc.getName());
                        placeUnitSalePlan.setPlaceId(puc.getPlaceId());
                        placeUnitSalePlan.setStatus(Constants.BYTE_ZERO); // 未定价
                        thisCUSalePlans.add(placeUnitSalePlan);
                    }
                }

                if (thisCUSalePlans.size() > 0) {
                    result.addAll(thisCUSalePlans);
                }
            }
        }

        return result;
    }

    /**
     * 根据营业时间和签约状况组合可销售计划列表
     *
     * @param placeId
     * @param placeUnitList
     * @return
     */
    public List<PlaceUnitSalePlan> getAllUnitSalePlanList(Integer placeId, List<TbBizPlaceUnit> placeUnitList, int timeInterval) {

        List<PlaceUnitSalePlan> result = new ArrayList<PlaceUnitSalePlan>();
        // 获取营业时间
        Map<Integer, List<PlaceUnitTime>> unitTimeMap = getSplitPlaceUnitTimeByUnitId(placeId, timeInterval);
        // 根据场馆ID获取合同明细 key:placeUnitId
        Map<Integer, List<TbBizPlaceBuyContractDetail>> contractDetailMap = getPlaceContractDetailGroupByUnitId(placeId);
        // 签约状况
        for (TbBizPlaceUnit bizPlaceUnit : placeUnitList) {
            List<PlaceUnitSalePlan> unitSalePlans = new ArrayList<PlaceUnitSalePlan>();
            if (contractDetailMap.containsKey(bizPlaceUnit.getId())) {
                List<TbBizPlaceBuyContractDetail> contractDetailList = contractDetailMap.get(bizPlaceUnit.getId());
                for (TbBizPlaceBuyContractDetail detail : contractDetailList) {
                    if (PlaceConstants.BUY_TYPE_WHOLE.equals(detail.getBuyType()) || PlaceConstants.BUY_TYPE_GROUP.equals(detail.getBuyType())) {
                        // 整馆和包片购买方式  按营业时间返回销售计划
                        if (unitTimeMap != null && unitTimeMap.containsKey(bizPlaceUnit.getId())) {
                            unitSalePlans = organizeSalePlan(unitTimeMap.get(bizPlaceUnit.getId()), bizPlaceUnit);
                        } else {
                            logger.warn(bizPlaceUnit.getName() + "场地没有维护营业时间");
                        }
                        break;
                    }
                    if (PlaceConstants.BUY_TYPE_TIME.equals(detail.getBuyType()) ||
                            PlaceConstants.BUY_TYPE_TRUE_TIME.equals(detail.getBuyType()) ||
                            PlaceConstants.BUY_TYPE_FALSE_TIME.equals(detail.getBuyType()) ) {
                        // 时段买入方式 只有签约时段作为可销售计划
                        PlaceUnitSalePlan placeUnitSalePlan = new PlaceUnitSalePlan();
                        placeUnitSalePlan.setStartTime(DateTimeUtils.convertDate2String("HH:mm:ss", detail.getBuyStartTime()));
                        placeUnitSalePlan.setEndTime(DateTimeUtils.convertDate2String("HH:mm:ss", detail.getBuyEndTime()));
                        placeUnitSalePlan.setTimeType(detail.getDateRange());
                        placeUnitSalePlan.setPlaceUnitId(bizPlaceUnit.getId());
                        placeUnitSalePlan.setPlaceUnitName(bizPlaceUnit.getName());
                        placeUnitSalePlan.setPlaceId(bizPlaceUnit.getPlaceId());
                        placeUnitSalePlan.setStatus(Constants.BYTE_ZERO); // 未定价
                        unitSalePlans.add(placeUnitSalePlan);
                    }
                }
            }
            result.addAll(unitSalePlans);
        }
        return result;
    }

    /**
     * 获取场馆经营运动类型
     *
     * @param placeId
     * @return
     */
    public PlaceCategoryVo getPlaceCategory(Integer placeId) {
        PlaceCategoryVo placeCategoryVo = new PlaceCategoryVo();
        TbBizPlace place = placeMapper.selectByPrimaryKey(placeId);
        TbBizPlaceCategoryExample tbBizPlaceCategoryExample = new TbBizPlaceCategoryExample();
        TbBizPlaceCategoryExample.Criteria tbBizPlaceCategoryCriteria = tbBizPlaceCategoryExample.createCriteria();
        tbBizPlaceCategoryCriteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceCategory> tbBizPlaceCategoryList = tbBizPlaceCategoryMapper.selectByExample(tbBizPlaceCategoryExample);
        if (tbBizPlaceCategoryList != null && tbBizPlaceCategoryList.size() > 0) {
            Set<Integer> placeCategorySet = new HashSet<Integer>();
            for (TbBizPlaceCategory tbBizPlaceCategory : tbBizPlaceCategoryList) {
                placeCategorySet.add(tbBizPlaceCategory.getCategoryId());
            }
            placeCategoryVo.setCategoryIdSet(placeCategorySet);
        }
        placeCategoryVo.setPlaceId(placeId);
        placeCategoryVo.setPlaceName(place.getName());
        if (place.getBusinessMode() != null){
            placeCategoryVo.setBusinessMode(place.getBusinessMode().intValue());
        }
        return placeCategoryVo;
    }

    /**
     * 保存场地销售计划（单个）
     *
     * @param placeUnitSalePlan
     * @return
     */
    public List<String> saveSinglePlaceSalePlan(PlaceUnitSalePlan placeUnitSalePlan, int period, Byte unitType) {
        List<String> errorMessage = new ArrayList<String>();
        if (placeUnitSalePlan != null) {
            List<Integer> baseUnitIds = null;

            if (placeUnitSalePlan.getId() != null) {
                // 修改销售计划模板
                TbBizPlaceUnitSalePlanMain oraPlaceUnitSalePlan = placeUnitSalePlanMainMapper.selectByPrimaryKey(placeUnitSalePlan.getId());
               /* if (oraPlaceUnitSalePlan.getPrice() != null &&
                        placeUnitSalePlan.getPrice() != null &&
                        oraPlaceUnitSalePlan.getPrice().compareTo(placeUnitSalePlan.getPrice()) != 0) {
                    //价格发生变更
                    oraPlaceUnitSalePlan.setVersion(oraPlaceUnitSalePlan.getVersion() + 1);
                }*/
                oraPlaceUnitSalePlan.setTimeType(placeUnitSalePlan.getTimeType());
                oraPlaceUnitSalePlan.setPrice(placeUnitSalePlan.getPrice());
                oraPlaceUnitSalePlan.setMemberPrice(placeUnitSalePlan.getMemberPrice());
                oraPlaceUnitSalePlan.setUpdateUid(placeUnitSalePlan.getUid());
                oraPlaceUnitSalePlan.setUpdateTime(Calendar.getInstance().getTime());
                placeUnitSalePlanMainMapper.updateByPrimaryKey(oraPlaceUnitSalePlan);
                // 价格模板发生变化时，同步到销售计划表
                if (null != oraPlaceUnitSalePlan.getPrice()) {
                    // 如果是组合场地,先获取子场地Id集合
                    if (UNIT_TYPE_COMBINE.equals(unitType)) {
                        TbBizPlaceUnitCombine unitCombine = placeUnitCombineMapper.selectByPrimaryKey(oraPlaceUnitSalePlan.getPlaceUnitId());
                        if (null != unitCombine) {
                            baseUnitIds = PlaceUtil.splitIds(unitCombine.getBaseUnits());
                        }
                    }

                    // 同步到销售计划表
                    // 修改部分和新增部分分开处理
                    executorService.execute(new UpdateSalePlanThread(oraPlaceUnitSalePlan, vPlaceMapper));
                    executorService.execute(new SyncSalePlanThread(oraPlaceUnitSalePlan, placeUnitSalePlanMapper, period, unitType, baseUnitIds));
                }
            } else {
                TbBizPlaceUnitSalePlanMainExample tbBizPlaceUnitSalePlanMainExample = new TbBizPlaceUnitSalePlanMainExample();
                TbBizPlaceUnitSalePlanMainExample.Criteria tbBizPlaceUnitSalePlanMainCriteria = tbBizPlaceUnitSalePlanMainExample.createCriteria();
                tbBizPlaceUnitSalePlanMainCriteria.andPlaceIdEqualTo(placeUnitSalePlan.getPlaceId());
                tbBizPlaceUnitSalePlanMainCriteria.andPlaceUnitIdEqualTo(placeUnitSalePlan.getPlaceUnitId());

                TbBizPlaceUnitSalePlanMain tbBizPlaceUnitSalePlanMain = new TbBizPlaceUnitSalePlanMain();
                tbBizPlaceUnitSalePlanMain.setPlaceId(placeUnitSalePlan.getPlaceId());
                tbBizPlaceUnitSalePlanMain.setPlaceUnitId(placeUnitSalePlan.getPlaceUnitId());

                if (UNIT_TYPE_BASE.equals(unitType)) {
                    TbBizPlaceUnit unit = placeUnitMapper.selectByPrimaryKey(placeUnitSalePlan.getPlaceUnitId());
                    if (null != unit) {
                        tbBizPlaceUnitSalePlanMain.setPlaceUnitName(unit.getName());
                        tbBizPlaceUnitSalePlanMain.setCategoryId((int) unit.getCategoryId());
                        tbBizPlaceUnitSalePlanMainCriteria.andCategoryIdEqualTo((int) unit.getCategoryId());
                    }
                } else if (UNIT_TYPE_COMBINE.equals(unitType)) {
                    TbBizPlaceUnitCombine unitCombine = placeUnitCombineMapper.selectByPrimaryKey(placeUnitSalePlan.getPlaceUnitId());
                    if (null != unitCombine) {
                        tbBizPlaceUnitSalePlanMain.setPlaceUnitName(unitCombine.getName());
                        tbBizPlaceUnitSalePlanMain.setCategoryId((int) unitCombine.getCategoryId());
                        baseUnitIds = PlaceUtil.splitIds(unitCombine.getBaseUnits());
                        tbBizPlaceUnitSalePlanMainCriteria.andCategoryIdEqualTo((int) unitCombine.getCategoryId());
                    }
                }

                tbBizPlaceUnitSalePlanMain.setPrice(placeUnitSalePlan.getPrice());
                tbBizPlaceUnitSalePlanMain.setMemberPrice(placeUnitSalePlan.getMemberPrice());
                tbBizPlaceUnitSalePlanMain.setStartTime(DateTimeUtils.convertString2Date("HH:mm:ss", placeUnitSalePlan.getStartTime()));
                tbBizPlaceUnitSalePlanMain.setEndTime(DateTimeUtils.convertString2Date("HH:mm:ss", placeUnitSalePlan.getEndTime()));
                tbBizPlaceUnitSalePlanMain.setVersion(Constants.ZERO); // 初始版本号为0
                tbBizPlaceUnitSalePlanMain.setIsEffective(Constants.BYTE_ONE); // 有效的
                tbBizPlaceUnitSalePlanMain.setTimeType(placeUnitSalePlan.getTimeType());
                tbBizPlaceUnitSalePlanMain.setCreateUid(placeUnitSalePlan.getUid());
                tbBizPlaceUnitSalePlanMain.setCreateTime(Calendar.getInstance().getTime());
                tbBizPlaceUnitSalePlanMain.setUpdateUid(placeUnitSalePlan.getUid());
                tbBizPlaceUnitSalePlanMain.setUpdateTime(Calendar.getInstance().getTime());

                tbBizPlaceUnitSalePlanMain.setUnitType(unitType);

                tbBizPlaceUnitSalePlanMainCriteria.andStartTimeEqualTo(DateTimeUtils.convertString2Date("HH:mm:ss", placeUnitSalePlan.getStartTime()));
                tbBizPlaceUnitSalePlanMainCriteria.andEndTimeEqualTo(DateTimeUtils.convertString2Date("HH:mm:ss", placeUnitSalePlan.getEndTime()));
                tbBizPlaceUnitSalePlanMainCriteria.andTimeTypeEqualTo(placeUnitSalePlan.getTimeType());
                tbBizPlaceUnitSalePlanMainCriteria.andUnitTypeEqualTo(unitType);
                List<TbBizPlaceUnitSalePlanMain> tbBizPlaceUnitSalePlanMainList = placeUnitSalePlanMainMapper.selectByExample(tbBizPlaceUnitSalePlanMainExample);
                if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanMainList)){
                    placeUnitSalePlanMainMapper.insert(tbBizPlaceUnitSalePlanMain);
                } else {
                    tbBizPlaceUnitSalePlanMain.setId(tbBizPlaceUnitSalePlanMainList.get(0).getId());
                    tbBizPlaceUnitSalePlanMain.setVersion(tbBizPlaceUnitSalePlanMainList.get(0).getVersion()+1); // 版本号+1
                    placeUnitSalePlanMainMapper.updateByExampleSelective(tbBizPlaceUnitSalePlanMain,tbBizPlaceUnitSalePlanMainExample);
                }

                if (null != tbBizPlaceUnitSalePlanMain.getPrice()) {
                    // 同步到销售计划表
                    //syncSalePlan(tbBizPlaceUnitSalePlanMain);
                    executorService.execute(new SyncSalePlanThread(tbBizPlaceUnitSalePlanMain, placeUnitSalePlanMapper, period, unitType, baseUnitIds));
                }
            }
        }
        return errorMessage;
    }

    /**
     * 场馆销售计划同步
     *
     * @param placeId    场馆Id
     * @param periodWeek 同步周期数
     */
    public void copySalePlanFromModel(Integer placeId, Integer periodWeek) {
        if (null != placeId) {
            if (null == periodWeek) {
                periodWeek = PlaceConstants.DEFAULT_PRICE_WEEK_PERIOD;
            }

            List<TbBizPlaceUnitSalePlanMain> salePlanModelList = this.getPlaceSalePlanTemplate(placeId, null, null, null);  // 包括基本场和组合场
            if (salePlanModelList == null || salePlanModelList.size() <= 0) {
                return;
            }

            // 先把该场馆的所有组合场地的子场信息读取回来
            Map<Integer, List<Integer>> buId2BaseUnitIds = new HashMap<>();

            TbBizPlaceUnitCombineExample example = new TbBizPlaceUnitCombineExample();
            TbBizPlaceUnitCombineExample.Criteria criteria = example.createCriteria();
            criteria.andPlaceIdEqualTo(placeId);
            List<TbBizPlaceUnitCombine> cus = placeUnitCombineMapper.selectByExample(example);
            if (cus != null && cus.size() > 0) {
                for (TbBizPlaceUnitCombine cu : cus) {
                    String baseUnits = cu.getBaseUnits();
                    if (baseUnits != null && !baseUnits.isEmpty()) {
                        buId2BaseUnitIds.put(cu.getId(), PlaceUtil.splitIds(baseUnits));
                    }
                }
            }

            int templateSize = salePlanModelList.size();
            int idx = 1;

            for (TbBizPlaceUnitSalePlanMain template : salePlanModelList) {
                // 更新已存在的销售计划
                List<TbBizPlaceUnitSalePlan> salePlanList = getPlaceUnitSalePlanByTemplateId(template.getId(),null);
                for (TbBizPlaceUnitSalePlan salePlan : salePlanList) {
                    salePlan.setPrice(template.getPrice());
                    salePlan.setMemberPrice(template.getMemberPrice());
                    salePlan.setUpdateUid(template.getUpdateUid());
                    salePlan.setUpdateTime(Calendar.getInstance().getTime());
                    // 如果是组合销售计划且sub_salePlans为空,则需要修复下
                    if (UNIT_TYPE_COMBINE.equals(salePlan.getUnitType())) {
                        String subSaleIds = salePlan.getSubSaleplans();
                        if (subSaleIds == null || subSaleIds.isEmpty()) {
                            logger.error("发现组合销售计划:{}的子销售计划为空", salePlan.getSaleId());

                            List<Integer> baseUnitIds = buId2BaseUnitIds.get(template.getPlaceUnitId());
                            if (baseUnitIds != null && baseUnitIds.size() > 0) {
                                List<String> saleIds = new ArrayList<>();
                                for (Integer buId : baseUnitIds) {
                                    saleIds.add(CommonUtils.createSaleID(buId, salePlan.getDate(), template.getStartTime(),template.getEndTime()));
                                }
                                salePlan.setSubSaleplans(StringUtil.join("|", saleIds));
                            } else {
                                logger.error("数据库中无法获取组合场:{}的子场地信息", salePlan.getSaleId());
                            }
                        }
                    }
                    if (template.getBundleNo() != null){
                        if (template.getBundleNo() == 0){
                            salePlan.setBundleNo(0);
                        } else {
                            String bundleNo = template.getPlaceUnitId()+""+template.getBundleNo();
                            salePlan.setBundleNo(Integer.valueOf(bundleNo));
                        }
                    }

                    placeUnitSalePlanMapper.updateByPrimaryKey(salePlan);
                }

                // 按指定周期同步新增的部分
                Integer dayOfWeek = transferDayOfWeek(template.getTimeType());
                Calendar nowDate = Calendar.getInstance(); // 当前日期
                String hour = DateTimeUtils.convertDate2String("HH", template.getStartTime());
                for (int i = 0; i <= periodWeek; i++) {
                    Calendar calendar = Calendar.getInstance(Locale.CHINA);
                    calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
                    calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
                    calendar.add(Calendar.DAY_OF_WEEK, 7 * i);
                    // n小时之前场地价格不可修改
                    int pricingInAdvanceHour = 1; // TODO
                    if (!isCanPricing(nowDate.getTime(), calendar.getTime(), pricingInAdvanceHour)) {
                        // 指定时间之前不能定价
                        continue;
                    }
                    TbBizPlaceUnitSalePlan salePlan = new TbBizPlaceUnitSalePlan();
                    salePlan.setDate(calendar.getTime());
                    salePlan.setSaleId(CommonUtils.createSaleID(template.getPlaceUnitId(), calendar.getTime(), template.getStartTime(),template.getEndTime())); // 销售计划Id
                    salePlan.setSalePlanMainId(template.getId());
                    salePlan.setStatus(PlaceConstants.PLACE_PREORDER_STATUS); // 状态：未预定
                    salePlan.setCategoryId(template.getCategoryId());
                    salePlan.setTimeType(template.getTimeType());
                    salePlan.setPlaceId(template.getPlaceId());
                    salePlan.setPlaceUnitId(template.getPlaceUnitId());
                    salePlan.setPlaceUnitName(template.getPlaceUnitName());
                    salePlan.setPrice(template.getPrice());
                    salePlan.setMemberPrice(template.getMemberPrice());
                    salePlan.setPlaceId(template.getPlaceId());
                    salePlan.setStartTime(template.getStartTime());
                    salePlan.setEndTime(template.getEndTime());
                    salePlan.setVersion(template.getVersion());
                    salePlan.setIsEffective(Constants.BYTE_ONE);
                    salePlan.setCreateUid(template.getCreateUid());
                    salePlan.setCreateTime(Calendar.getInstance().getTime());
                    salePlan.setUpdateUid(template.getUpdateUid());
                    salePlan.setUpdateTime(Calendar.getInstance().getTime());
                    if (template.getBundleNo() != null){
                        if (template.getBundleNo() == 0){
                            salePlan.setBundleNo(0);
                        } else {
                            String bundleNo = template.getPlaceUnitId()+""+template.getBundleNo();
                            salePlan.setBundleNo(Integer.valueOf(bundleNo));
                        }
                    }

                    salePlan.setUnitType(template.getUnitType());

                    // 如果是组合场地的需要保存 子saleId集合
                    if (UNIT_TYPE_COMBINE.equals(template.getUnitType())) {
                        List<Integer> baseUnitIds = buId2BaseUnitIds.get(template.getPlaceUnitId());
                        if (baseUnitIds != null && baseUnitIds.size() > 0) {
                            List<String> saleIds = new ArrayList<>();
                            for (Integer buId : baseUnitIds) {
                                saleIds.add(CommonUtils.createSaleID(buId, calendar.getTime(), template.getStartTime(), template.getEndTime()));
                            }
                            salePlan.setSubSaleplans(StringUtil.join("|", saleIds));
                        } else {
                            logger.error("无法获取组合场地:{}的子场地信息及其子saleIds", template.getPlaceUnitId());
                            continue;
                        }
                    }

                    try {
                        placeUnitSalePlanMapper.insert(salePlan);
                    } catch (Exception e) {
                        logger.error("销售计划同步失败:mainId：{} startTime:{} 失败:{}", template.getId(), template.getStartTime(), e.getMessage());
                    }
                }
            }
            logger.info("处理完:{}/{}销售计划模板", idx++, templateSize);
        }
    }


    /**
     * 保存运营规则
     *
     * @param placeOperationRuleVo
     */
    @Override
    public boolean savePlaceOperationRule(PlaceOperationRuleVo placeOperationRuleVo) {
        int result = 0;
        if (null != placeOperationRuleVo) {
            if (placeOperationRuleVo.getPlaceRuleId() != null) {
                TbBizPlaceRule rule = tbBizPlaceRuleMapper.selectByPrimaryKey(placeOperationRuleVo.getPlaceRuleId());
                if (null != rule) {
                    rule.setAllOrderMaxTime(placeOperationRuleVo.getMaxPermitOrderHoursOneDay()); // 一天可预订的最大时段数
                    rule.setOnceOrderMaxTime(placeOperationRuleVo.getMaxPermitOrderHoursOneTime()); // 一次可预订的最大时段数
                    rule.setUnsubscribeMaxNumber(placeOperationRuleVo.getMaxUnsubscribeNumOneDay());// 一天最大退订次数
                    rule.setCancelMaxNumber(placeOperationRuleVo.getMaxCancelNumOneDay()); // 一天最大取消订场次数
                    rule.setUnsubscribeTime(placeOperationRuleVo.getMaxInAdvanceRefundHours()); // 提前退订的小时数
                    rule.setIsContainOtherDate(placeOperationRuleVo.getIsDisplayOtherTime()); // 是否显示 "更多日期"
                    rule.setSyncSalePlanCycle(placeOperationRuleVo.getSyncSalePlanCycle());
                    rule.setCreateUid(placeOperationRuleVo.getUid());
                    rule.setCreateTime(Calendar.getInstance().getTime());
                    rule.setUpdateUid(placeOperationRuleVo.getUid());
                    rule.setUpdateTime(Calendar.getInstance().getTime());
                    result = tbBizPlaceRuleMapper.updateByPrimaryKey(rule);
                }
            } else {
                TbBizPlaceRule rule = new TbBizPlaceRule();
                rule.setAllOrderMaxTime(placeOperationRuleVo.getMaxPermitOrderHoursOneDay()); // 一天可预订的最大时段数
                rule.setOnceOrderMaxTime(placeOperationRuleVo.getMaxPermitOrderHoursOneTime()); // 一次可预订的最大时段数
                rule.setUnsubscribeMaxNumber(placeOperationRuleVo.getMaxUnsubscribeNumOneDay());// 一天最大退订次数
                rule.setCancelMaxNumber(placeOperationRuleVo.getMaxCancelNumOneDay()); // 一天最大取消订场次数
                rule.setUnsubscribeTime(placeOperationRuleVo.getMaxInAdvanceRefundHours()); // 提前退订的小时数
                rule.setIsContainOtherDate(placeOperationRuleVo.getIsDisplayOtherTime()); // 是否显示 "更多日期"
                rule.setSyncSalePlanCycle(placeOperationRuleVo.getSyncSalePlanCycle());
                rule.setPlaceId(placeOperationRuleVo.getPlaceId());
                rule.setUpdateUid(placeOperationRuleVo.getUid());
                rule.setUpdateTime(Calendar.getInstance().getTime());
                result = tbBizPlaceRuleMapper.insertSelective(rule);
            }
        }
        return result > 0;
    }

    /**
     * 获取场馆运营规则
     * @param placeId
     * @return
     */
    @Override
    public PlaceOperationRuleVo getPlaceOperationRule(Integer placeId) {
        PlaceOperationRuleVo ruleVo = new PlaceOperationRuleVo();
        TbBizPlaceRuleExample example = new TbBizPlaceRuleExample();
        TbBizPlaceRuleExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceRule> ruleList = tbBizPlaceRuleMapper.selectByExample(example);
        if (null != ruleList && ruleList.size() > 0) {
            TbBizPlaceRule rule = ruleList.get(0);
            ruleVo.setIsDisplayOtherTime(rule.getIsContainOtherDate());
            ruleVo.setMaxPermitOrderHoursOneDay(rule.getAllOrderMaxTime()); // 一天可预订的最大时段数
            ruleVo.setMaxPermitOrderHoursOneTime(rule.getOnceOrderMaxTime()); // 一天最大退订次数
            ruleVo.setMaxUnsubscribeNumOneDay(rule.getUnsubscribeMaxNumber()); // 一天最大取消订场次数
            ruleVo.setMaxCancelNumOneDay(rule.getCancelMaxNumber());  // 提前退订的小时数
            ruleVo.setMaxInAdvanceRefundHours(rule.getUnsubscribeTime()); // 是否显示 "更多日期"
            ruleVo.setPlaceId(placeId);
            ruleVo.setSyncSalePlanCycle(rule.getSyncSalePlanCycle()); // 同步销售计划周期
            ruleVo.setPlaceRuleId(rule.getId());
            ruleVo.setIsDisplayOtherTime(rule.getIsContainOtherDate());
        }
        return ruleVo;
    }


    /**
     * 保存场馆销售计划(批量)
     *
     * @param salePlanList
     * @return
     */
    @Override
    public List<String> savePlaceSalePlanBatch(List<PlaceUnitSalePlan> salePlanList, int period, Byte unitType) {
        List<String> errorMessage = new ArrayList<String>();
        if (null == salePlanList || salePlanList.size() == 0) {
            errorMessage.add("销售计划不能为空");
            return errorMessage;
        }
        for (PlaceUnitSalePlan salePlan : salePlanList) {
            try {
                saveSinglePlaceSalePlan(salePlan, period, unitType);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        return errorMessage;
    }

    public boolean getMinPrice(PlaceUnitSalePlan placeUnitSalePlan) {
        try {
            List<TbBizPlaceUnitSalePlan> minPrices = this.salePlanMapper.getBizPlaceMinPrice(placeUnitSalePlan);

            if(com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(minPrices)){

                TbBizPlace tbBizPlace = new TbBizPlace();
                tbBizPlace.setId(placeUnitSalePlan.getPlaceId());
                Double minPrice = null ;
                if (!org.springframework.util.StringUtils.isEmpty(minPrices.get(0).getPrice())){
                    minPrice = minPrices.get(0).getPrice().doubleValue();
                }
//                minPrice = org.springframework.util.StringUtils.isEmpty(minPrice) ? 0d : minPrice;//未签约，没有订单  不能给0
                tbBizPlace.setLowestPrice(minPrice);
                this.tbBizPlaceMapper.updateByPrimaryKeySelective(tbBizPlace);
                // 更新tb_biz_place_category最低价
                TbBizPlaceCategoryExample example = new TbBizPlaceCategoryExample();
                TbBizPlaceCategoryExample.Criteria criteria = example.createCriteria();
                criteria.andPlaceIdEqualTo(placeUnitSalePlan.getPlaceId());
                criteria.andCategoryIdEqualTo(placeUnitSalePlan.getCategoryId());
                TbBizPlaceCategory tbBizPlaceCategory = new TbBizPlaceCategory();
                tbBizPlaceCategory.setLowestPrice(minPrice);
                tbBizPlaceCategory.setPlaceId(placeUnitSalePlan.getPlaceId());
                tbBizPlaceCategory.setCategoryId(placeUnitSalePlan.getCategoryId());
                this.tbBizPlaceCategoryMapper.updateByExampleNoId(tbBizPlaceCategory,example);
            }else{
                logger.debug("最低价为空");
            }

        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 根据模板id查询销售计划
     * @param templateId  模板Id
     * @param baseDate 基准日期
     * @return
     */
    public List<TbBizPlaceUnitSalePlan> getPlaceUnitSalePlanByTemplateId(Integer templateId,Date baseDate) {
        TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
        criteria.andSalePlanMainIdEqualTo(templateId);
        criteria.andIsEffectiveEqualTo(Constants.BYTE_ONE);
        if (null == baseDate){
            criteria.andDateGreaterThan(new Date());
        } else {
            criteria.andDateGreaterThan(baseDate);
        }
        return placeUnitSalePlanMapper.selectByExample(example);
    }

    /**
     * 销售计划模板数据同步到销售计划表
     *
     * @param unitSalePlanMain
     */
    private void syncSalePlan(TbBizPlaceUnitSalePlanMain unitSalePlanMain) {
        int periodWeek = PlaceConstants.DEFAULT_PRICE_WEEK_PERIOD; // TODO 系统参数获取
        TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
        criteria.andSalePlanMainIdEqualTo(unitSalePlanMain.getId());
        criteria.andTimeTypeEqualTo(unitSalePlanMain.getTimeType());
        criteria.andIsEffectiveEqualTo(Constants.BYTE_ONE);
        criteria.andDateGreaterThan(new Date());
        // 如果已经存在于销售计划表中，更新没有过时的记录
        List<TbBizPlaceUnitSalePlan> salePlanList = placeUnitSalePlanMapper.selectByExample(example);
        for (TbBizPlaceUnitSalePlan salePlan : salePlanList) {
            salePlan.setPrice(unitSalePlanMain.getPrice());
            salePlan.setMemberPrice(unitSalePlanMain.getMemberPrice());
            salePlan.setUpdateUid(unitSalePlanMain.getUpdateUid());
            salePlan.setUpdateTime(Calendar.getInstance().getTime());
            placeUnitSalePlanMapper.updateByPrimaryKey(salePlan);
        }
        // 按指定周期同步新增的部分
        Integer dayOfWeek = transferDayOfWeek(unitSalePlanMain.getTimeType());
        Calendar nowDate = Calendar.getInstance(); // 当前日期
        String hour = DateTimeUtils.convertDate2String("HH", unitSalePlanMain.getStartTime());
        for (int i = 0; i <= periodWeek; i++) {
            Calendar calendar = Calendar.getInstance(Locale.CHINA);
            calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
            calendar.add(Calendar.DAY_OF_WEEK, 7 * i);
            // n小时之前场地价格不可修改
            int pricingInAdvanceHour = 1; // TODO
            if (!isCanPricing(nowDate.getTime(), calendar.getTime(), pricingInAdvanceHour)) {
                // 指定时间之前不能定价
                continue;
            }
            TbBizPlaceUnitSalePlan salePlan = new TbBizPlaceUnitSalePlan();
            salePlan.setDate(calendar.getTime());
            salePlan.setSaleId(CommonUtils.createSaleID(unitSalePlanMain.getPlaceUnitId(), calendar.getTime(), unitSalePlanMain.getStartTime(), unitSalePlanMain.getEndTime())); // 销售计划Id
            salePlan.setSalePlanMainId(unitSalePlanMain.getId());
            salePlan.setStatus(Constants.BYTE_ONE);
            salePlan.setIsEffective(Constants.BYTE_ONE);
            salePlan.setCategoryId(unitSalePlanMain.getCategoryId());
            salePlan.setTimeType(unitSalePlanMain.getTimeType());
            salePlan.setPlaceId(unitSalePlanMain.getPlaceId());
            salePlan.setPlaceUnitId(unitSalePlanMain.getPlaceUnitId());
            salePlan.setPlaceUnitName(unitSalePlanMain.getPlaceUnitName());
            salePlan.setPrice(unitSalePlanMain.getPrice());
            salePlan.setMemberPrice(unitSalePlanMain.getMemberPrice());
            salePlan.setPlaceId(unitSalePlanMain.getPlaceId());
            salePlan.setStartTime(unitSalePlanMain.getStartTime());
            salePlan.setEndTime(unitSalePlanMain.getEndTime());
            salePlan.setVersion(unitSalePlanMain.getVersion());
            salePlan.setCreateUid(unitSalePlanMain.getCreateUid());
            salePlan.setCreateTime(Calendar.getInstance().getTime());
            salePlan.setUpdateUid(unitSalePlanMain.getUpdateUid());
            salePlan.setUpdateTime(Calendar.getInstance().getTime());
            try {
                placeUnitSalePlanMapper.insert(salePlan);
            } catch (Exception e) {
                logger.error("销售计划同步失败:mainId：{} startTime:{} 失败:{}", unitSalePlanMain.getId(), unitSalePlanMain.getStartTime(), e.getMessage());
            }
        }

    }

    /**
     * 将数据库保存的星期表示数转换为适用于日历的整数
     *
     * @param timeType
     * @return
     */
    private Integer transferDayOfWeek(String timeType) {
        Integer dayOfWeek = 0;
        if (StringUtils.isNotEmpty(timeType)) {
            dayOfWeek = Integer.valueOf(timeType); // 星期：1,2,3....7
            if (null != dayOfWeek) {
                // 因为DAY_OF_WEEK 星期日为一周的第一天，赋值时做一次转换
                if (dayOfWeek == 7) {
                    dayOfWeek = 1;
                } else if (dayOfWeek < 7) {
                    dayOfWeek = dayOfWeek + 1;
                }
            }
        }
        return dayOfWeek;
    }

    /**
     * 判断指定销售计划时间是否能变更价格
     *
     * @param fromTime
     * @param toTime
     * @param pricingInAdvanceHour
     * @return
     */
    private boolean isCanPricing(Date fromTime, Date toTime, int pricingInAdvanceHour) {
        int periodHour = DateUtils.dateDiffHour(fromTime, toTime);
        return periodHour >= pricingInAdvanceHour;
    }

    /**
     * 根据场馆Id和类目ID获取场地可销售列表，用于定价
     *
     * @param placeId
     * @param categoryId
     * @return
     */
    public List<PlaceUnitSalePlanVo> getPlaceUnitSalePlanVoGroupByUnit(Integer placeId, Byte categoryId) {
        TbBizPlaceUnitExample example = new TbBizPlaceUnitExample();
        TbBizPlaceUnitExample.Criteria criterial = example.createCriteria();
        if (placeId != null) {
            criterial.andPlaceIdEqualTo(placeId);
        }
        if (categoryId != null) {
            criterial.andCategoryIdEqualTo(categoryId);
        }
        criterial.andIsSignEqualTo(Constants.BYTE_ONE);
        // 获取场馆下已签约场地列表
        List<TbBizPlaceUnit> placeUnitList = placeUnitMapper.selectByExample(example);
        // 如果存在销售计划 从销售计划表查询
        List<PlaceUnitSalePlanVo> placeUnitSalePlanVoList = this.getPlaceSalePlanVo(placeId);

        if (placeUnitSalePlanVoList == null || placeUnitSalePlanVoList.size() == 0) {
            // 不存在销售计划
            // 获取营业时间
            Map<Integer, List<PlaceUnitTime>> unitTimeMap = getSplitPlaceUnitTimeByUnitId(placeId, 60); // TODO
            // 根据场馆ID获取合同明细 key:placeUnitId
            Map<Integer, List<TbBizPlaceBuyContractDetail>> contractDetailMap = getPlaceContractDetailGroupByUnitId(placeId);
            // 签约状况
            for (TbBizPlaceUnit bizPlaceUnit : placeUnitList) {
                PlaceUnitSalePlanVo placeUnitSalePlanVo = null;
                List<PlaceUnitSalePlan> unitSalePlans = new ArrayList<PlaceUnitSalePlan>();
                boolean flg = false;
                if (contractDetailMap.containsKey(bizPlaceUnit.getId())) {
                    List<TbBizPlaceBuyContractDetail> contractDetailList = contractDetailMap.get(bizPlaceUnit.getId());
                    for (TbBizPlaceBuyContractDetail detail : contractDetailList) {
                        if (PlaceConstants.BUY_TYPE_WHOLE.equals(detail.getBuyType()) || PlaceConstants.BUY_TYPE_GROUP.equals(detail.getBuyType())) {
                            // 整馆和包片购买方式  按营业时间返回销售计划
                            if (unitTimeMap != null && unitTimeMap.containsKey(bizPlaceUnit.getId())) {
                                placeUnitSalePlanVo = organizeSalePlanVo(unitTimeMap.get(bizPlaceUnit.getId()), bizPlaceUnit);
                                if (placeUnitSalePlanVo != null) {
                                    placeUnitSalePlanVoList.add(placeUnitSalePlanVo);
                                }
                            } else {
                                logger.error(bizPlaceUnit.getName() + "场地没有维护营业时间");
                            }
                            flg = true;
                            break;
                        }
                        if (PlaceConstants.BUY_TYPE_TIME.equals(detail.getBuyType()) ||
                                PlaceConstants.BUY_TYPE_TRUE_TIME.equals(detail.getBuyType()) ||
                                PlaceConstants.BUY_TYPE_FALSE_TIME.equals(detail.getBuyType()) ) {
                            // 时段买入方式 只有签约时段作为可销售计划
                            if (placeUnitSalePlanVo == null) {
                                placeUnitSalePlanVo = new PlaceUnitSalePlanVo();
                                placeUnitSalePlanVo.setUnitId(bizPlaceUnit.getId());
                                placeUnitSalePlanVo.setCategoryId(categoryId);
                            }
                            PlaceUnitSalePlan placeUnitSalePlan = new PlaceUnitSalePlan();
                            placeUnitSalePlan.setStartTime(DateTimeUtils.convertDate2String("HH:mm:ss", detail.getBuyStartTime()));
                            placeUnitSalePlan.setEndTime(DateTimeUtils.convertDate2String("HH:mm:ss", detail.getBuyEndTime()));
                            placeUnitSalePlan.setTimeType(detail.getDateRange());
                            placeUnitSalePlan.setPlaceUnitId(bizPlaceUnit.getId());
                            placeUnitSalePlan.setPlaceId(bizPlaceUnit.getPlaceId());
                            placeUnitSalePlan.setStatus(Constants.BYTE_ZERO); // 未定价
                            unitSalePlans.add(placeUnitSalePlan);
                        }
                    }
                    if (flg) {
                        continue;
                    }
                    if (placeUnitSalePlanVo != null) {
                        placeUnitSalePlanVo.setSalePlanList(unitSalePlans);
                        placeUnitSalePlanVoList.add(placeUnitSalePlanVo);
                    }
                }
            }
        }
        return placeUnitSalePlanVoList;
    }

    private List<PlaceUnitSalePlanVo> getPlaceSalePlanVo(Integer placeId) {
        List<PlaceUnitSalePlanVo> result = new ArrayList<PlaceUnitSalePlanVo>();
        Map<Integer, List<PlaceUnitSalePlan>> salePlanMap = this.getPlaceSalePlanByPlaceId(placeId);
        if (salePlanMap == null || salePlanMap.size() == 0) {
            return result;
        }
        Iterator it = salePlanMap.entrySet().iterator();
        while (it.hasNext()) {
            PlaceUnitSalePlanVo placeUnitSalePlanVo = new PlaceUnitSalePlanVo();
            Map.Entry entry = (Map.Entry) it.next();
            Integer unitId = (Integer) entry.getKey();
            placeUnitSalePlanVo.setUnitId(unitId);
            List<PlaceUnitSalePlan> salePlans = (List<PlaceUnitSalePlan>) entry.getValue();
            placeUnitSalePlanVo.setSalePlanList(salePlans);
            result.add(placeUnitSalePlanVo);
        }
        return result;
    }

    /**
     * 根据场馆id和经营范围获取销售计划信息
     * @param placeId
     * @param categoryId
     * @return
     */
    public List<PlaceUnitSalePlan> getPlaceSalePlanFromDB(Integer placeId, Byte categoryId, Byte unitType) {
        List<PlaceUnitSalePlan> salePlansResult = new ArrayList<PlaceUnitSalePlan>();
        List<TbBizPlaceUnitSalePlanMain> salePlanList = this.getPlaceSalePlanTemplate(placeId, categoryId, null, unitType);
        for (TbBizPlaceUnitSalePlanMain oracSalePlan : salePlanList) {
            PlaceUnitSalePlan salePlan = new PlaceUnitSalePlan();
            salePlan.setPlaceId(placeId);
            salePlan.setId(oracSalePlan.getId());
            salePlan.setPlaceUnitId(oracSalePlan.getPlaceUnitId());
            salePlan.setPlaceUnitName(oracSalePlan.getPlaceUnitName());
            salePlan.setTimeType(oracSalePlan.getTimeType());
            salePlan.setStartTime(DateTimeUtils.convertDate2String("HH:mm:ss", oracSalePlan.getStartTime()));
            salePlan.setEndTime(DateTimeUtils.convertDate2String("HH:mm:ss", oracSalePlan.getEndTime()));
            salePlan.setPrice(oracSalePlan.getPrice());
            salePlan.setMemberPrice(oracSalePlan.getMemberPrice());
            salePlan.setStatus(oracSalePlan.getStatus()); // 已定价
            salePlansResult.add(salePlan);
        }
        return salePlansResult;
    }

    /**
     * 将销售计划按场地Id分组
     *
     * @param placeId
     * @return
     */
    public Map<Integer, List<PlaceUnitSalePlan>> getPlaceSalePlanByPlaceId(Integer placeId) {
        List<PlaceUnitSalePlan> salePlansResult = null;
        Map<Integer, List<PlaceUnitSalePlan>> salePlanMap = new HashMap<Integer, List<PlaceUnitSalePlan>>();
        List<TbBizPlaceUnitSalePlanMain> salePlanList = this.getPlaceSalePlanTemplate(placeId, null, null, UNIT_TYPE_BASE);
        for (TbBizPlaceUnitSalePlanMain oracSalePlan : salePlanList) {
            PlaceUnitSalePlan salePlan = new PlaceUnitSalePlan();
            salePlan.setPlaceId(placeId);
            salePlan.setPlaceUnitId(oracSalePlan.getPlaceUnitId());
            salePlan.setStartTime(DateTimeUtils.convertDate2String("HH:mm:ss", oracSalePlan.getStartTime()));
            salePlan.setEndTime(DateTimeUtils.convertDate2String("HH:mm:ss", oracSalePlan.getEndTime()));
            salePlan.setPrice(oracSalePlan.getPrice());
            salePlan.setStatus(Constants.BYTE_ONE); // 已定价
            if (salePlanMap.containsKey(oracSalePlan.getPlaceUnitId())) {
                salePlansResult = salePlanMap.get(oracSalePlan.getPlaceUnitId());
            } else {
                salePlansResult = new ArrayList<PlaceUnitSalePlan>();
            }
            salePlansResult.add(salePlan);
            salePlanMap.put(oracSalePlan.getPlaceUnitId(), salePlansResult);
        }
        return salePlanMap;
    }

    /**
     * 从数据库查询销售计划模板
     *
     * @param placeId
     * @return
     */
    public List<TbBizPlaceUnitSalePlanMain> getPlaceSalePlanTemplate(Integer placeId, Byte categoryId, Integer weekDay, Byte unitType) {
        TbBizPlaceUnitSalePlanMainExample example = new TbBizPlaceUnitSalePlanMainExample();
        TbBizPlaceUnitSalePlanMainExample.Criteria criteria = example.createCriteria();
        if (placeId != null) {
            criteria.andPlaceIdEqualTo(placeId);
        }
        if (categoryId != null) {
            criteria.andCategoryIdEqualTo((int) categoryId);
        }
        // weekDay不为空时，只查询一周内指定weekDay 的销售计划
        if (weekDay != null){
            criteria.andTimeTypeEqualTo(String.valueOf(weekDay));
        }
        criteria.andIsEffectiveEqualTo(Constants.BYTE_ONE); // 有效的

        if (unitType != null) {
            criteria.andUnitTypeEqualTo(unitType);
        }

        List<TbBizPlaceUnitSalePlanMain> salePlans = placeUnitSalePlanMainMapper.selectByExample(example);
        return salePlans;
    }

    /**
     * 整馆和包片购入方式按营业时间封装销售计划
     *
     * @param unitTimeList
     * @param bizPlaceUnit
     * @return
     */
    private List<PlaceUnitSalePlan> organizeSalePlan(List<PlaceUnitTime> unitTimeList, TbBizPlaceUnit bizPlaceUnit) {
        List<PlaceUnitSalePlan> unitSalePlans = new ArrayList<PlaceUnitSalePlan>();
        for (PlaceUnitTime unitTime : unitTimeList) {
            PlaceUnitSalePlan salePlan = new PlaceUnitSalePlan();
            salePlan.setStartTime(unitTime.getStartTime());
            salePlan.setEndTime(unitTime.getEndTime());
            salePlan.setTimeType(unitTime.getTimeType());
            salePlan.setPlaceUnitId(bizPlaceUnit.getId());
            salePlan.setPlaceUnitName(bizPlaceUnit.getName());
            salePlan.setPlaceId(bizPlaceUnit.getPlaceId());
            salePlan.setStatus(Constants.BYTE_ZERO); // 未定价
            unitSalePlans.add(salePlan);
        }
        return unitSalePlans;
    }

    private PlaceUnitSalePlanVo organizeSalePlanVo(List<PlaceUnitTime> unitTimeList, TbBizPlaceUnit bizPlaceUnit) {
        PlaceUnitSalePlanVo placeUnitPrice = new PlaceUnitSalePlanVo();
        placeUnitPrice.setUnitId(bizPlaceUnit.getId());              // 场地单元ID
        placeUnitPrice.setCategoryId(bizPlaceUnit.getCategoryId());  // 项目
        List<PlaceUnitSalePlan> unitSalePlans = new ArrayList<PlaceUnitSalePlan>();
        for (PlaceUnitTime unitTime : unitTimeList) {
            PlaceUnitSalePlan salePlan = new PlaceUnitSalePlan();
            salePlan.setStartTime(unitTime.getStartTime());
            salePlan.setEndTime(unitTime.getEndTime());
            salePlan.setTimeType(unitTime.getTimeType());
            salePlan.setPlaceUnitId(bizPlaceUnit.getId());
            salePlan.setPlaceId(bizPlaceUnit.getPlaceId());
            salePlan.setStatus(Constants.BYTE_ZERO); // 未定价
            unitSalePlans.add(salePlan);
        }
        placeUnitPrice.setSalePlanList(unitSalePlans);
        return placeUnitPrice;
    }

    /**
     * 根据场馆ID获取合同明细（按场地Id分组）
     *
     * @param placeId
     * @return
     */
    public Map<Integer, List<TbBizPlaceBuyContractDetail>> getPlaceContractDetailGroupByUnitId(Integer placeId) {
        Map<Integer, List<TbBizPlaceBuyContractDetail>> resultMap = new HashMap<Integer, List<TbBizPlaceBuyContractDetail>>();
        TbBizPlaceBuyContractDetailExample example = new TbBizPlaceBuyContractDetailExample();
        TbBizPlaceBuyContractDetailExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        criteria.andFinishDateGreaterThan(new Date()); // TODO
        criteria.andIsDeleteEqualTo(PlaceConstants.NO);//过滤未废弃的合同   [废弃：is_delete=0;中止：is_delete 不变]
        List<TbBizPlaceBuyContractDetail> tbBizPlaceBuyContractDetailList = placeBuyContractDetailMapper.selectByExample(example);
        List<TbBizPlaceBuyContractDetail> contractDetailList = null;
        for (TbBizPlaceBuyContractDetail detail : tbBizPlaceBuyContractDetailList) {
            if (resultMap.containsKey(detail.getPlaceUnitId())) {
                contractDetailList = resultMap.get(detail.getPlaceUnitId());
            } else {
                contractDetailList = new ArrayList<TbBizPlaceBuyContractDetail>();
            }
            contractDetailList.add(detail);
            resultMap.put(detail.getPlaceUnitId(), contractDetailList);
        }
        return resultMap;
    }

    /**
     * 根据场馆获取营业时段（按星期分组）
     *
     * @param placeId
     * @param section
     * @return
     */
    private Map<String, List<PlaceUnitTime>> getSplitPlaceUnitTimeByWeek(Integer placeId, Integer section) {
        Map<String, List<PlaceUnitTime>> result = new HashMap<String, List<PlaceUnitTime>>(); // 按星期分装到map中
        List<PlaceUnitTime> placeUnitTimeList = null;
        List<TbBizPlaceUnitTime> placeUnitPrimeTimeList = this.getPlaceUnitTimeList(placeId);
        if (!placeUnitPrimeTimeList.isEmpty()) {
            for (TbBizPlaceUnitTime placeUnitTime : placeUnitPrimeTimeList) {
                String start = placeUnitTime.getStartTime();
                String end = placeUnitTime.getEndTime();
                List<String> timeList = DateTimeUtils.getIntervalTimeList(start, end, section);
                if (result.containsKey(placeUnitTime.getTimeType())) {
                    placeUnitTimeList = result.get(placeUnitTime.getTimeType());
                } else {
                    placeUnitTimeList = new ArrayList<PlaceUnitTime>();
                }
                if (!timeList.isEmpty()) {
                    PlaceUnitTime unitTime;
                    for (int n = 0; n < timeList.size() - 1; n++) {
                        unitTime = new PlaceUnitTime();
                        unitTime.setStartTime(timeList.get(n));
                        unitTime.setEndTime(timeList.get(n + 1));
                        unitTime.setPlaceUnitId(placeUnitTime.getPlaceUnitId());
                        unitTime.setTimeType(placeUnitTime.getTimeType());
                        //0为非黄金时段，1为黄金时段
                        unitTime.setIsPrimeTime(placeUnitTime.getIsPrimeTime());
                        placeUnitTimeList.add(unitTime);
                    }
                    result.put(placeUnitTime.getTimeType(), placeUnitTimeList);
                }
            }
        }
        return result;
    }

    /**
     * 根据场馆获取营业时段（按场地Id分组）
     *
     * @param placeId
     * @param section
     * @return
     */
    private Map<Integer, List<PlaceUnitTime>> getSplitPlaceUnitTimeByUnitId(Integer placeId, Integer section) {
        Map<Integer, List<PlaceUnitTime>> result = new HashMap<Integer, List<PlaceUnitTime>>();
        List<PlaceUnitTime> placeUnitTimeList = null;
        List<TbBizPlaceUnitTime> placeUnitPrimeTimeList = this.getPlaceUnitTimeList(placeId);
        if (!placeUnitPrimeTimeList.isEmpty()) {
            for (TbBizPlaceUnitTime placeUnitTime : placeUnitPrimeTimeList) {
                String start = placeUnitTime.getStartTime();
                String end = placeUnitTime.getEndTime();
                List<String> timeList = DateTimeUtils.getIntervalTimeList(start, end, section);
                if (result.containsKey(placeUnitTime.getPlaceUnitId())) {
                    placeUnitTimeList = result.get(placeUnitTime.getPlaceUnitId());
                } else {
                    placeUnitTimeList = new ArrayList<PlaceUnitTime>();
                }
                if (!timeList.isEmpty()) {
                    PlaceUnitTime unitTime;
                    for (int n = 0; n < timeList.size() - 1; n++) {
                        unitTime = new PlaceUnitTime();
                        unitTime.setStartTime(timeList.get(n));
                        unitTime.setEndTime(timeList.get(n + 1));
                        unitTime.setPlaceUnitId(placeUnitTime.getPlaceUnitId());
                        unitTime.setTimeType(placeUnitTime.getTimeType());
                        //0为非黄金时段，1为黄金时段
                        unitTime.setIsPrimeTime(placeUnitTime.getIsPrimeTime());
                        placeUnitTimeList.add(unitTime);
                    }
                    result.put(placeUnitTime.getPlaceUnitId(), placeUnitTimeList);
                }
            }
        }
        return result;
    }

    /**
     * 获取场馆下场地单元营业时间
     *
     * @param placeId
     * @return
     */
    public List<TbBizPlaceUnitTime> getPlaceUnitTimeList(Integer placeId) {
        TbBizPlaceUnitTimeExample example = new TbBizPlaceUnitTimeExample();
        example.createCriteria().andPlaceIdEqualTo(placeId);
        List<TbBizPlaceUnitTime> list = placeUnitTimeMapper.selectByExample(example);
        return list;
    }

    /**
     * 查询合同明细  isEffective 0:无效  1：有效
     *
     * @param placeId
     * @param isEffective
     * @return
     */
    @Override
    public List<TbBizPlaceBuyContractDetail> getPlaceContractDetail(Integer placeId, boolean isEffective) {
        TbBizPlaceBuyContractDetailExample example = new TbBizPlaceBuyContractDetailExample();
        TbBizPlaceBuyContractDetailExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        if (isEffective) {
            criteria.andIsDeleteEqualTo(Constants.BYTE_ZERO);
            criteria.andFinishDateGreaterThan(new Date());
        }
        List<TbBizPlaceBuyContractDetail> tbBizPlaceBuyContractDetailList = placeBuyContractDetailMapper.selectByExample(example);
        return tbBizPlaceBuyContractDetailList;
    }

    /**
     * 删除场馆
     * @param placeId
     * @return
     */
    public APIResponse deletePlace(Integer placeId) {

        TbBizPlace tbBizPlace = new TbBizPlace();
        tbBizPlace.setIsDelete(Constants.IS_YES);
        tbBizPlace.setId(placeId);
        placeMapper.updateByPrimaryKeySelective(tbBizPlace);

        TbBizPlaceUnit tbBizPlaceUnit = new TbBizPlaceUnit();
        tbBizPlaceUnit.setIsDelete(Constants.IS_DELETE_TRUE);
        tbBizPlaceUnit.setPlaceId(placeId);
        placeUnitMapper.updateByPrimaryKeySelective(tbBizPlaceUnit);

        // 删除场馆单元相关信息
        TbBizPlaceUnitStatisticsExample tbBizPlaceUnitStatisticsExample = new TbBizPlaceUnitStatisticsExample();
        TbBizPlaceUnitStatisticsExample.Criteria tbBizPlaceUnitStatisticsCriteria = tbBizPlaceUnitStatisticsExample.createCriteria();
        tbBizPlaceUnitStatisticsCriteria.andPlaceIdEqualTo(placeId);
        unitStatisticsMapper.deleteByExample(tbBizPlaceUnitStatisticsExample);

        searchService.deleteDocById(placeId, PlaceConstants.SOLR_INDEX_PLAN);
        searchService.deleteDocById(placeId, PlaceConstants.SOLR_INDEX_PLACE);

        return APIResponse.returnSuccess();
    }

    /**
     * 删除场地
     * @param placeUnitId
     * @return
     */
    public APIResponse deletePlaceUnit(Integer placeUnitId) {

        TbBizPlaceUnit tbBizPlaceUnit = new TbBizPlaceUnit();
        tbBizPlaceUnit.setIsDelete(Constants.IS_DELETE_TRUE);
        tbBizPlaceUnit.setId(placeUnitId);
        placeUnitMapper.updateByPrimaryKeySelective(tbBizPlaceUnit);
        // 删除场馆单元统计信息
        TbBizPlaceUnitStatisticsExample tbBizPlaceUnitStatisticsExample = new TbBizPlaceUnitStatisticsExample();
        TbBizPlaceUnitStatisticsExample.Criteria tbBizPlaceUnitStatisticsCriteria = tbBizPlaceUnitStatisticsExample.createCriteria();
        tbBizPlaceUnitStatisticsCriteria.andPlaceUnitIdEqualTo(placeUnitId);
        unitStatisticsMapper.deleteByExample(tbBizPlaceUnitStatisticsExample);

        TbBizPlaceUnit placeUnit = placeUnitMapper.selectByPrimaryKey(placeUnitId);
        if (!org.springframework.util.StringUtils.isEmpty(placeUnit)){
            TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
            tbBizPlaceUnitSalePlanExample.createCriteria().andIsEffectiveEqualTo(PlaceConstants.IS_EFFECTIVE_YES)
                    .andPlaceUnitIdEqualTo(placeUnitId);
            List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = tbBizPlaceUnitSalePlanMapper
                    .selectByExample(tbBizPlaceUnitSalePlanExample);
            if (CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlanList)){
                List<String> ids = new ArrayList<>();
                for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList){
                    ids.add(tbBizPlaceUnitSalePlan.getSaleId());
                }
                TbBizPlace bizPlace = new TbBizPlace();
                bizPlace.setId(placeUnit.getPlaceId());
                searchService.addPlaceIndex(bizPlace, ids);
            }
        }


        return APIResponse.returnSuccess();
    }

    /**
     * 保存场馆相关信息
     * @param placeFromDataVo
     * @return
     */
    @Override
    @Transactional
    public TbBizPlace savePlaceInfo(PlaceFromDataVo placeFromDataVo) {
        List<TbPlaceImage> tbPlaceImageList = placeFromDataVo.getPlace_attach_list();
        TbBizPlace tbBizPlace = new TbBizPlace();
        TbBizPlaceAttach tbBizPlaceAttach = new TbBizPlaceAttach();
        tbBizPlace.setName(placeFromDataVo.getName());
        tbBizPlace.setAddress(placeFromDataVo.getAddress());
        tbBizPlace.setCityId(placeFromDataVo.getCityId());
        tbBizPlace.setProvinceId(placeFromDataVo.getProvinceId());
        tbBizPlace.setDistrictId(placeFromDataVo.getDistrictId());
        tbBizPlace.setComment(placeFromDataVo.getComment());
        tbBizPlace.setLat(placeFromDataVo.getLat());
        tbBizPlace.setLng(placeFromDataVo.getLng());
        tbBizPlace.setContact(placeFromDataVo.getContact()); // 运营负责人
        tbBizPlace.setPhone(placeFromDataVo.getPhone());  // 场馆电话
        tbBizPlace.setBusinessMode(placeFromDataVo.getBusinessMode()); // 自营/联营
        tbBizPlace.setIsShelves(Constants.ZERO); // 未上架
        tbBizPlace.setSupplierId(placeFromDataVo.getSupplierId());
        tbBizPlace.setSourceId(PlaceConstants.SOURCE_PLACE_BUSINESS); // 商务录入，跟原来的数据区分开
        tbBizPlace.setIsMultiUnit(Constants.BYTE_ONE);
        tbBizPlace.setType(Constants.BYTE_ZERO);
        tbBizPlace.setIsOpen(Constants.BYTE_ZERO);
        tbBizPlace.setIsSign(Constants.BYTE_ZERO);
        tbBizPlace.setStatus(1);
        tbBizPlace.setIsRecommend(Constants.BYTE_ZERO);
        tbBizPlace.setIsDelete(0);
        Short s = 0;
        tbBizPlace.setPriority(s);
        tbBizPlace.setIsSign(Constants.BYTE_ZERO);
        tbBizPlace.setType(Constants.BYTE_ZERO);
        tbBizPlace.setUid(placeFromDataVo.getUid());
        tbBizPlace.setBlockindex(PlaceTools.calIndexByLatLon(tbBizPlace.getLat(), tbBizPlace.getLng()));
        tbBizPlace.setSeaAreaType(PlaceConstants.SEA_AREA_TYPE_PUBLIC);
        tbBizPlace.setPlaceScore(0d);
        tbBizPlace.setLowestPrice(0d);
        tbBizPlace.setSignupCount(0);
        tbBizPlace.setCommentCount(0);
        TbAdminUser tbAdminUser = adminUserMapper.selectByPrimaryKey(placeFromDataVo.getUid());
        if (tbAdminUser != null){
            tbBizPlace.setDeptId(tbAdminUser.getDeptId());
        }

        if(tbPlaceImageList != null && tbPlaceImageList.size() > 0){
            tbBizPlace.setBizPlaceUrl(tbPlaceImageList.get(0).getUrl());
        }
        placeMapper.insert(tbBizPlace);//插入营业场所表



        tbBizPlaceAttach.setPlaceId(tbBizPlace.getId()); //从已经插入场馆表中返回的数据获得
        tbBizPlaceAttach.setIsPrimeLocation(placeFromDataVo.getIsPrimeLocation());
        tbBizPlaceAttach.setManageType(placeFromDataVo.getManageType());
        tbBizPlaceAttach.setPlaceLevel(placeFromDataVo.getPlaceLevel());
        tbBizPlaceAttach.setStartBusinessTime(placeFromDataVo.getStartBusinessTime());
        tbBizPlaceAttach.setRemainTime(placeFromDataVo.getRemainTime());
        tbBizPlaceAttach.setIsContainBath(placeFromDataVo.getIsContainBath());
        tbBizPlaceAttach.setIsContainWater(placeFromDataVo.getIsContainWater());
        tbBizPlaceAttach.setIsContainWifi(placeFromDataVo.getIsContainWifi());
        tbBizPlaceAttach.setIsContainHeating(placeFromDataVo.getIsContainHeating());
        tbBizPlaceAttach.setIsContainAc(placeFromDataVo.getIsContainAc());
        tbBizPlaceAttach.setIsContainAdArea(placeFromDataVo.getIsContainAdArea());
        tbBizPlaceAttach.setParkNum(placeFromDataVo.getParkNum());
        tbBizPlaceAttach.setIsParkFree(placeFromDataVo.getIsParkFree());
        tbBizPlaceAttach.setOwnership(placeFromDataVo.getOwnership()); //场馆所有权
        tbBizPlaceAttach.setBusinessHourStart(placeFromDataVo.getBusinessHourStart());
        tbBizPlaceAttach.setBusinessHourEnd(placeFromDataVo.getBusinessHourEnd());
        tbBizPlaceAttach.setHolidayBusinessHourStart(placeFromDataVo.getHolidayBusinessHourStart());
        tbBizPlaceAttach.setHolidayBusinessHourEnd(placeFromDataVo.getHolidayBusinessHourEnd());
        tbBizPlaceAttach.setIsContainPrimeTime(Constants.BYTE_ZERO);
        tbBizPlaceAttach.setIsVip(placeFromDataVo.getIsVip());
        tbBizPlaceAttach.setIsVipHouse(placeFromDataVo.getIsVipHouse());
        tbBizPlaceAttach.setIsTrain(placeFromDataVo.getIsTrain());
        tbBizPlaceAttach.setIsLockerRoom(placeFromDataVo.getIsLockerRoom());
        tbBizPlaceAttach.setPlaceGoods(placeFromDataVo.getPlaceGoods());
        tbBizPlaceAttach.setBookingConsultPhone(placeFromDataVo.getBookingConsultPhone()); // 订场咨询电话
        tbBizPlaceAttach.setIsVipShare(Constants.NO);
        if(com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(placeFromDataVo.getTrafficInfoList())){
            List<RespBizPlaceTrafficInfo> trafficInfoList = placeFromDataVo.getTrafficInfoList();
            StringBuffer trafficInfoBuffer = new StringBuffer();
            for (RespBizPlaceTrafficInfo respBizPlaceTrafficInfo : trafficInfoList) {
                trafficInfoBuffer.append(respBizPlaceTrafficInfo.getType());
                trafficInfoBuffer.append(":");
                trafficInfoBuffer.append(respBizPlaceTrafficInfo.getDescribe());
                trafficInfoBuffer.append("|");
            }
            if (trafficInfoBuffer.length() > 1){
                tbBizPlaceAttach.setTrafficInfo(trafficInfoBuffer.substring(0,trafficInfoBuffer.length() - 1));
            }
        }


        if(placeFromDataVo.getPlaceCategoryList() != null && placeFromDataVo.getPlaceCategoryList().size() > 0){
            List<Integer> categorySaleTabList = new ArrayList<>();
            categorySaleTabList.addAll(placeFromDataVo.getPlaceCategoryList());
            categorySaleTabList.add(5);
            categorySaleTabList.add(6);
            tbBizPlaceAttach.setSaleTab(org.apache.commons.lang.StringUtils.join(categorySaleTabList.toArray(),","));
        }


        tbBizPlaceAttachMapper.insert(tbBizPlaceAttach);//插入片场附属表
        //插入场地图片资源表

        if(tbPlaceImageList != null && tbPlaceImageList.size() > 0){
            for (TbPlaceImage tbPlaceImage : tbPlaceImageList){
                Byte bb = 1;
                tbPlaceImage.setContentType(bb);
                tbPlaceImage.setTopicId(tbBizPlace.getId());
                tbPlaceImage.setTitle(placeFromDataVo.getName() + "图片");
                tbPlaceImage.setSize(0);
                tbPlaceImageMapper.insert(tbPlaceImage);
            }
        }

        //插入场馆经营范围表
        List<Integer> placeCategoryList = placeFromDataVo.getPlaceCategoryList();
        if(placeCategoryList != null && placeCategoryList.size() > 0){
            for (Integer categoryId : placeCategoryList) {
                TbBizPlaceCategory tbBizPlaceCategory = new TbBizPlaceCategory();
                tbBizPlaceCategory.setPlaceId(tbBizPlace.getId());
                tbBizPlaceCategory.setCategoryId(categoryId);
                tbBizPlaceCategory.setMinSaleTimeUnit(Constants.BYTE_ONE); // 默认1小时起售
                tbBizPlaceCategory.setStartSaleTimeType(Constants.BYTE_ONE); // 默认整点起
                tbBizPlaceCategoryMapper.insertSelective(tbBizPlaceCategory);
            }
        }

        return tbBizPlace;
    }

    /**
     * 获取片场详情接口
     * @param placeUnitId
     * @return
     * @throws Exception
     */
    @Override
    public APIResponse getPlaceUnitDetailData(int placeUnitId)  throws Exception{
        TbBizPlaceUnitExample tbBizPlaceUnitExample = new TbBizPlaceUnitExample();
        TbBizPlaceUnitExample.Criteria tbBizPlaceUnitCriteria = tbBizPlaceUnitExample.createCriteria();
        tbBizPlaceUnitCriteria.andIdEqualTo(placeUnitId);
        tbBizPlaceUnitCriteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbBizPlaceUnit> tbBizPlaceUnitList = placeUnitMapper.selectByExample(tbBizPlaceUnitExample);
        TbBizPlaceUnitVo tbBizPlaceUnitVo = new TbBizPlaceUnitVo();

        if(tbBizPlaceUnitList != null && tbBizPlaceUnitList.size() > 0){
            for (TbBizPlaceUnit tbBizPlaceUnit : tbBizPlaceUnitList){
                BeanUtils.copyProperties(tbBizPlaceUnitVo, tbBizPlaceUnit);
                TbBizPlaceUnitTimeExample tbBizPlaceUnitTimeExample = new TbBizPlaceUnitTimeExample();
                TbBizPlaceUnitTimeExample.Criteria tbBizPlaceUnitTimeCriteria = tbBizPlaceUnitTimeExample.createCriteria();
                tbBizPlaceUnitTimeCriteria.andPlaceUnitIdEqualTo(tbBizPlaceUnit.getId());
                tbBizPlaceUnitTimeCriteria.andPlaceIdEqualTo(tbBizPlaceUnit.getPlaceId());
                List<TbBizPlaceUnitTime> tbBizPlaceUnitTimeList = placeUnitTimeMapper.selectByExample(tbBizPlaceUnitTimeExample);
                tbBizPlaceUnitVo.setPlace_unit_time_list(tbBizPlaceUnitTimeList);
            }
        }
        return  APIResponse.returnSuccess(tbBizPlaceUnitVo);
    }


    /**
     * 根据场馆ID获取场馆附属信息
     *
     * @param placeId
     * @return
     */
    public TbBizPlaceAttach getBizPlaceAttach(Integer placeId) {
        TbBizPlaceAttachExample example = new TbBizPlaceAttachExample();
        TbBizPlaceAttachExample.Criteria criterial = example.createCriteria();
        if (placeId != null) {
            criterial.andPlaceIdEqualTo(placeId);
        }
        List<TbBizPlaceAttach> result = tbBizPlaceAttachMapper.selectByExample(example);
        if (result != null && result.size() > 0) {
            return result.get(0);
        } else {
            return null;
        }
    }

    /**
     * 根据场馆ID获取场馆商务代表
     *
     * @param placeId
     * @return
     */
    public TbBizPlaceRepresent getBizPlaceBussinessRepresent(Integer placeId) {
        TbBizPlaceRepresentExample example = new TbBizPlaceRepresentExample();
        TbBizPlaceRepresentExample.Criteria criterial = example.createCriteria();
        if (placeId != null) {
            criterial.andPlaceIdEqualTo(placeId);
            criterial.andIsEffectiveEqualTo(Constants.BYTE_ONE);
        }
        List<TbBizPlaceRepresent> result = tbBizPlaceRepresentMapper.selectByExample(example);
        if (result != null && result.size() > 0) {
            return result.get(0);
        } else {
            return null;
        }
    }


    /**
     * 根据uid获取当前职称
     *
     * @param uid
     * @return
     */
    public int getloginTitle(Integer uid) {
        return 5;
    }


    /**
     * 根据场馆Id获取场地列表
     *
     * @param placeId
     * @return
     */
    public List<TbBizPlaceUnit> getPlaceUnitByPlaceId(Integer placeId) {
        TbBizPlaceUnitExample example = new TbBizPlaceUnitExample();
        TbBizPlaceUnitExample.Criteria criterial = example.createCriteria();
        if (placeId != null) {
            criterial.andPlaceIdEqualTo(placeId);
            criterial.andIsDeleteEqualTo(Constants.BYTE_ZERO);
        }
        List<TbBizPlaceUnit> result = placeUnitMapper.selectByExample(example);
        return result;
    }


    /**
     * 获取场馆场地片数
     *
     * @param placeId
     * @return
     */
    public int countPlaceUnitByPlaceId(Integer placeId) {
        TbBizPlaceUnitExample example = new TbBizPlaceUnitExample();
        TbBizPlaceUnitExample.Criteria criterial = example.createCriteria();
        if (placeId != null) {
            criterial.andPlaceIdEqualTo(placeId);
            criterial.andIsDeleteEqualTo(Constants.BYTE_ZERO);
        }
        return placeUnitMapper.countByExample(example);
    }

    /**
     * 计算周黄金时长
     *
     * @param placeId
     * @return
     */
    public Double computePrimeTimeByWeek(Integer placeId) {
        BigDecimal resultTime = new BigDecimal(0);
        TbBizPlaceUnitStatisticsExample example = new TbBizPlaceUnitStatisticsExample();
        TbBizPlaceUnitStatisticsExample.Criteria criteria = example.createCriteria();
        if (placeId != null) {
            criteria.andPlaceIdEqualTo(placeId);
            List<TbBizPlaceUnitStatistics> result = unitStatisticsMapper.selectByExample(example);
            if (result != null && result.size() > 0) {
                for (TbBizPlaceUnitStatistics statistics : result) {
                    resultTime = resultTime.add(statistics.getWeekPrimeHourNum());
                }
            }
        }
       /* List<VPlaceTime> result = vPlaceMapper.getPrimeTimeByPlaceId(placeId, null);
        for (VPlaceTime p : result){
            if (PlaceConstants.DICT_TIME_TIME_WORKDAY.equals(p.getTimeType())){
                resultTime += p.getLengthOfTime() * 5;
            } else if (PlaceConstants.DICT_TIME_TIME_WEEKEND.equals(p.getTimeType())){
                resultTime += p.getLengthOfTime() * 2;
            }
        }*/
        return resultTime.doubleValue();
    }

    /**
     * 计算周销售时长
     *
     * @param placeAttach
     * @param unitNum
     * @return
     */
    public Double computeSaleTimeInWeek(TbBizPlaceAttach placeAttach, Integer unitNum) {
        Double lengthOfTime = 0d;
        List<VPlaceTime> result = vPlaceMapper.getBusinessTimeByPlaceId(placeAttach.getPlaceId());
        if (result != null && result.size() > 0) {
            VPlaceTime placeTime = result.get(0);
            lengthOfTime += placeTime.getLengthOfTime() * 5;
            lengthOfTime += placeTime.getLengthOfTimeHoliday() * 2;
            lengthOfTime *= unitNum;
        }

        return lengthOfTime;
    }

    /**
     * 根据type获取字典类型
     *
     * @param type
     * @return
     */
    public Map<String, String> getDictDisplayName(String type) {
        HashMap<String, String> map = new HashMap<String, String>();
        DictExample dictExample = new DictExample();
        DictExample.Criteria dictCriteria = dictExample.createCriteria();
        dictCriteria.andTagGroupEqualTo(type);
        List<Dict> result = this.dictMapper.selectDataValueByExample(dictExample);
        for (Dict dict : result) {
            map.put(dict.getDataKey(), dict.getDataValue());
        }
        return map;
    }


    public PageObj<List<TbBizPlace>> getPlacesRistorRecord(ReqPlaceSearch reqPlaceSearch) {
        Integer pageNums = 0;
        Integer pageSizes = Constants.DEFAULT_PAGE_SIZE;

        TbBizPlaceExample tbBizPlaceExample = new TbBizPlaceExample();
        TbBizPlaceExample.Criteria tbBizPlaceCriteria = tbBizPlaceExample.createCriteria();
        tbBizPlaceCriteria.andCityIdEqualTo(reqPlaceSearch.getCityId());
        tbBizPlaceCriteria.andNameLike("%" + reqPlaceSearch.getName() + "%");
        if (reqPlaceSearch.getPageNum() == null) {
            reqPlaceSearch.setPageNum(pageNums);
        }
        if (reqPlaceSearch.getPageSize() == null) {
            reqPlaceSearch.setPageSize(pageSizes);
        }
        int totalNum = placeMapper.countByExample(tbBizPlaceExample);
        tbBizPlaceExample.setPage(new Page(reqPlaceSearch.getPageNum() * reqPlaceSearch.getPageSize(), reqPlaceSearch.getPageSize(), totalNum));
        List<TbBizPlace> list = placeMapper.selectByExample(tbBizPlaceExample);

        //List<PlaceInfo> returnList = new ArrayList<PlaceInfo>();
        /*for (TbBizPlace place:list){
            PlaceInfo placeInfo=new PlaceInfo();
            TbBizPlaceAttach placeAttach = this.getBizPlaceAttach(place.getId());
            placeInfo.setPlaceId(place.getId());
            placeInfo.setManageTypeName(placeAttach.getManageType());

        }*/


        PageObj<List<TbBizPlace>> result = PageObj.create(totalNum, pageNums, pageSizes, list); // TODO
        return result;


    }


    /**
     * 查询授权场馆
     *
     * @param userId
     * @return
     */
    @Override
    public List<TbBizPlaceAuthUser> getAuthPlaceForUser(Integer userId) {
        //Set<Integer> placeIdSet = new HashSet<Integer>();
        TbBizPlaceAuthUserExample tbBizPlaceAuthUserExample = new TbBizPlaceAuthUserExample();
        TbBizPlaceAuthUserExample.Criteria tbBizPlaceAuthUserExampleCriteria = tbBizPlaceAuthUserExample.createCriteria();
        tbBizPlaceAuthUserExampleCriteria.andUserIdEqualTo(userId);
        List<TbBizPlaceAuthUser> tbBizPlaceAuthUserList = tbBizPlaceAuthUserMapper.selectByExample(tbBizPlaceAuthUserExample);
       /* for (TbBizPlaceAuthUser auth : tbBizPlaceAuthUserList) {
            placeIdSet.add(auth.getPlaceId());
        }*/
        return tbBizPlaceAuthUserList;
    }


    /**
     * 锁定场馆
     * @param place
     * @param user
     * @return
     */
    @Override
    public List<String> lockPlace(TbBizPlace place, TbAdminUser user) {
        List<String> errorMessage = new ArrayList<String>();
        if (null != place){
            // 场馆海域类型设置为私海
            if (isPerimitLock(place, user)){
                place.setSeaAreaType(PlaceConstants.SEA_AREA_TYPE_PRIVATE);
                placeMapper.updateByPrimaryKeySelective(place);
                if (null != user) {
                    // 商务代表和场馆关联
                    TbBizPlaceRepresent tbBizPlaceRepresent = new TbBizPlaceRepresent();
                    tbBizPlaceRepresent.setBusinessRepresent(user.getTrueName());
                    tbBizPlaceRepresent.setIsEffective(Constants.BYTE_ONE);
                    tbBizPlaceRepresent.setUserId(user.getId()); // 商务代表uid
                    tbBizPlaceRepresent.setUid(user.getId());    // 当前操作人
                    tbBizPlaceRepresent.setPlaceId(place.getId());
                    tbBizPlaceRepresent.setCreateTime(Calendar.getInstance().getTime());
                    tbBizPlaceRepresentMapper.insert(tbBizPlaceRepresent);
                }
                //记录场馆垃圾私海的时间
                //this.savePlaceJoinPrivateTime(place);
                logger.info("插入次数");
                periodService.importPeriodData(place.getId());
            }else{
                errorMessage.add("最多只能锁定20个场馆！");
            }
        }
        return errorMessage;
    }

    /**
     * 解除场馆锁定
     * @param place
     * @param user
     * @return
     */
    @Override
    @Transactional
    public List<String> unlockPlace(TbBizPlace place, TbAdminUser user) {
        List<String> errorMessage = new ArrayList<String>();
        if (null != place){
            // 商务代表和场馆关联
            TbBizPlaceRepresent tbBizPlaceRepresent = getBizPlaceBussinessRepresent(place.getId());
            tbBizPlaceRepresent.setIsEffective(Constants.BYTE_ZERO); // 设为无效
            tbBizPlaceRepresent.setUpdateTime(Calendar.getInstance().getTime());
            tbBizPlaceRepresentMapper.updateByPrimaryKey(tbBizPlaceRepresent);
            // 场馆海域类型设置为公海
            place.setSeaAreaType(PlaceConstants.SEA_AREA_TYPE_PUBLIC);
            placeMapper.updateByPrimaryKeySelective(place);

            tbBizPlacePeriodService.deletePeriodInfoByPlaceId(place.getId());
        }
        return errorMessage;
    }

/*
通过名字查询场馆，模糊查询
 */
    @Override
    public List<TbBizPlace> getPlaceInfoByName(String value,TbBizPlace place) {
        TbBizPlaceExample example =new TbBizPlaceExample();
        TbBizPlaceExample.Criteria criteria=example.createCriteria();
        if (value.equals("Like")) {
            criteria.andNameLike(place.getName());
        }
        if (value.equals("Equal")){
            criteria.andNameEqualTo(place.getName());
        }
        List<TbBizPlace> list=tbBizPlaceMapper.selectByExample(example);
        if (null != list && list.size()>0){
           return list;
        }
        return null;
    }

    /**
     * 获取商务场馆列表
     * @param uid
     * @param pageNum
     * @param pageSize
     * @param keywords
     * @return
     */
    @Override
    public List<TbBizPlace> getCommercePlaceList(Integer uid, Integer pageNum, Integer pageSize, String keywords) {
        int begin = pageNum * pageSize;
        List<TbBizPlace> placeList = vPlaceMapper.getCommercePlaceList(uid, keywords, begin, pageSize);
        return placeList;
    }

    public int countCommercePlace(Integer uid, String keywords) {
        return vPlaceMapper.countCommercePlace(uid, keywords);
    }

    /**
     * 判断是否允许锁定
     * @param place
     * @param user
     * @return
     */
    public boolean isPerimitLock(TbBizPlace place, TbAdminUser user) {
        int count = getPrivateSeaNum(user.getId());
        if (count>20){
            return false;
        }else{
            return true;
        }
    }



    public void savePlaceJoinPrivateTime(TbBizPlace place){
        TbBizPlacePeriodExample periodExample=new TbBizPlacePeriodExample();
        TbBizPlacePeriodExample.Criteria periodCriteria=periodExample.createCriteria();
        periodCriteria.andPlaceIdEqualTo(place.getId());
        List<TbBizPlacePeriod> listPeriod=tbBizPlacePeriodMapper.selectByExample(periodExample);
        TbBizPlacePeriod tp=new TbBizPlacePeriod();
        tp.setPlaceId(place.getId());
        tp.setJoinPrivateTime(new Date());
        if (null != listPeriod && listPeriod.size()>0){
            tbBizPlacePeriodMapper.updateByExampleSelective(tp,periodExample);
        }else{
            tbBizPlacePeriodMapper.insert(tp);
        }
    }



    /**
     * 获取商务代表私海容量
     * @param uid
     * @return
     */
    public Integer getPrivateSeaNum(Integer uid){
        Integer count = pMapper.getPrivateSeaByBusinessRep(uid);
        return count;
    }

    /*
任务调度： 1.锁定天数到期后，由私海状态改成公海状态
          2.合同过期的设置为断约
          3.当前时间大于合同结束时间，且大于的天数超过了场馆解锁规定的天数，则放回到公海
 */
    @Override
    public void updateStatus() {
        //锁定天数到期后，由私海状态改成公海状态
        TbBizPlacePeriodExample periodExample=new TbBizPlacePeriodExample();
        //TbBizPlacePeriodExample.Criteria criteria= periodExample.createCriteria();
        List<TbBizPlacePeriod> listPeriod= tbBizPlacePeriodMapper.selectByExample(periodExample);
        List<Integer> listPlaceId=new ArrayList<Integer>();
        for (TbBizPlacePeriod period :listPeriod){
            if (period.getJoinPrivateTime()!=null) {
                int days = DateUtils.dateDiffDay(period.getJoinPrivateTime(), new Date());
                if(period.getEndLockDays()!=null) {
                    if (days > period.getEndLockDays()) {
                        listPlaceId.add(period.getPlaceId());
                    }
                }
            }
        }
        if (listPlaceId!=null&&listPlaceId.size()>0){
            TbBizPlaceExample example=new TbBizPlaceExample();
            TbBizPlaceExample.Criteria eCriteria= example.createCriteria();
            eCriteria.andIdIn(listPlaceId);
            List<TbBizPlace> listPlace=placeMapper.selectByExample(example);
            if (listPlace!=null&&listPlace.size()>0){
                for (TbBizPlace place:listPlace){
                    TbBizPlace vo=new TbBizPlace();
                    vo.setId(place.getId());
                    vo.setSeaAreaType(PlaceConstants.SEA_AREA_TYPE_PUBLIC);
                    placeMapper.updateByPrimaryKeySelective(vo);
                    //设置商务代表状态
                    this.setRepresentStats(place);
                    //清理周期数据
                    tbBizPlacePeriodService.deletePeriodInfoByPlaceId(place.getId());
                }
            }
        }

        //查询有没合同到期的，有则设置为断约
        TbBizPlaceBuyContractDetail vo =new TbBizPlaceBuyContractDetail();
        vo.setIsSign(PlaceConstants.IS_SIGN_YES);
        List<TbBizPlaceBuyContractDetail> placeBuyList = pMapper.getPlaceMaxTime(vo);//已签约的合同
        Date currentTimeDate = new Date();
        for (TbBizPlaceBuyContractDetail detail:placeBuyList){
            Integer placeId=detail.getPlaceId();
            Date date= detail.getFinishDate();
            boolean flag= false;
            if (detail.getFinishDate()!=null) {
                flag = DateUtils.compare(currentTimeDate, detail.getFinishDate(), false);
            }
            //当前时间大于合同结束时间则合同已过期,状态改成断约
            if (flag==true){
                TbBizPlace tbBizPlace =new TbBizPlace();
                tbBizPlace.setId(placeId);
                tbBizPlace.setIsSign(PlaceConstants.IS_SIGN_BREAK);//断约；2
                pMapper.updateSeaArea(tbBizPlace);
            }
        }

        //查看断约的天数有没超过，场馆解锁规定的天数，有则放回到公海
        TbBizPlaceBuyContractDetail breakvo =new TbBizPlaceBuyContractDetail();
        //breakvo.setIsSign(PlaceConstants.IS_SIGN_BREAK);
        List<TbBizPlaceBuyContractDetail> listbreak = pMapper.getPlaceMaxTime(breakvo);//已断约的合同
        for (TbBizPlaceBuyContractDetail cvo:listbreak) {
            if (cvo.getFinishDate() != null) {
                Integer placeId = cvo.getPlaceId();
                Date date = cvo.getFinishDate();
                int days = DateUtils.dateDiffDay(cvo.getFinishDate(), new Date());
                TbBizPlacePeriodExample example = new TbBizPlacePeriodExample();
                TbBizPlacePeriodExample.Criteria perExample = example.createCriteria();
                perExample.andPlaceIdEqualTo(placeId);
                List<TbBizPlacePeriod> periodList = tbBizPlacePeriodMapper.selectByExample(example);
                if (periodList != null && periodList.size() > 0) {
                    TbBizPlacePeriod periodVo = periodList.get(0);
                    if (days > periodVo.getUnlockDays()) {
                        TbBizPlace tbBizPlace = new TbBizPlace();
                        tbBizPlace.setId(placeId);
                        this.setRepresentStats(tbBizPlace);
                        tbBizPlace.setSeaAreaType(PlaceConstants.SEA_AREA_TYPE_PUBLIC);
                        pMapper.updateSeaArea(tbBizPlace);
                        //清理周期数据
                        tbBizPlacePeriodService.deletePeriodInfoByPlaceId(placeId);
                    }
                }
            }
        }
    }

    public List<RespPlaceInfo> getCanSalePlace(Integer pageNum, Integer pageSize){
        return vPlaceMapper.getCanSalePlaceList(pageNum, pageSize);
    }

    @Override
    public void insertSalePlanBatch(List<TbBizPlaceUnitSalePlan> salePlanList) {
        vPlaceMapper.insertSalePlanBatch(salePlanList);
    }

    /**
     * 获取提供商信息
     * @return
     */
    @Override
    public PageObj<List<TbSupplier>> getSupplierData(ReqSupplierSearchVo reqSupplierSearchVo) {
        TbSupplierExample example=new TbSupplierExample();
        Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        TbSupplierExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        if (reqSupplierSearchVo != null){
            if (reqSupplierSearchVo.getCityId() != null){
                criteria.andCityIdEqualTo(reqSupplierSearchVo.getCityId());
            }
            if(reqSupplierSearchVo.getProvinceId() !=null){
                criteria.andProvinceIdEqualTo(reqSupplierSearchVo.getProvinceId());
            }
            if(reqSupplierSearchVo.getSupplierType() !=null){
                criteria.andSupplierTypeEqualTo(reqSupplierSearchVo.getSupplierType());
            }
            if (reqSupplierSearchVo.getPlaceSupplierType()!=null){
                criteria.andSupplierTypeEqualTo(reqSupplierSearchVo.getPlaceSupplierType());
            }
            if(reqSupplierSearchVo.getSupplierType() !=null){
                criteria.andSupplierTypeEqualTo(reqSupplierSearchVo.getSupplierType());
            }
            pageNum = reqSupplierSearchVo.getPageNum();
            pageSize = reqSupplierSearchVo.getPageSize();
            String keywords = reqSupplierSearchVo.getKey();

            if(StringUtils.isNotEmpty(keywords)){
                criteria.andNameLike("%" + keywords + "%");
            }
        }

        int total =tbSupplierMapper.countByExample(example);
        example.setOrderByClause("priority desc,id desc");
        example.setPage(new Page(pageNum * pageSize, pageSize,total));
        List<TbSupplier> records = tbSupplierMapper.selectByExample(example);
        PageObj<List<TbSupplier>> result = PageObj.create(total, pageNum, pageSize, records);
        return result;

    }

    /**
     * 获取区域信息
     * @param cityId
     * @return
     */
    @Override
    public APIResponse getDistrictData(int cityId) {
        try {
            TbDistrictExample tbDistrictExample = new TbDistrictExample();
            TbDistrictExample.Criteria tbDistrictCriteria = tbDistrictExample.createCriteria();
            tbDistrictCriteria.andCityIdEqualTo(cityId);
            tbDistrictExample.setOrderByClause("priority");
            List<TbDistrict> list = tbDistrictMapper.selectNameByExample(tbDistrictExample);
            return APIResponse.returnSuccess(list);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return APIResponse.returnFail(ApiResponseEnum.RESOURCE_NOT_FOUND);
    }


    /**
     * 场馆数据检查
     * @param placeFromDataVo
     * @return
     */
    @Override
    public APIResponse validatePlaceData(PlaceFromDataVo placeFromDataVo) {
        TbBizPlaceExample tbBizPlaceExample = new TbBizPlaceExample();
        TbBizPlaceExample.Criteria tbBizPlaceCriteria = tbBizPlaceExample.createCriteria();
        tbBizPlaceCriteria.andNameEqualTo(placeFromDataVo.getName());
        tbBizPlaceCriteria.andIsDeleteEqualTo(Constants.IS_NO);
        List<TbBizPlace> tbBizPlaceList =  placeMapper.selectByExample(tbBizPlaceExample);

        if(tbBizPlaceList != null && tbBizPlaceList.size() > 0){
            return APIResponse.returnFail("场馆名称已经存在!");
        }

        APIResponse apiResponse = ValidatorUtils.lengthValidateMustInput(placeFromDataVo.getName(), "场馆名称", 30);
        if( apiResponse != null ){
            return apiResponse;
        }

        apiResponse = ValidatorUtils.lengthValidate(placeFromDataVo.getName(), "场馆地址", 50);
        if( apiResponse != null ){
            return apiResponse;
        }

        apiResponse = ValidatorUtils.phone(placeFromDataVo.getPhone());
        if( apiResponse != null ){
            return apiResponse;
        }

        apiResponse = ValidatorUtils.isNumAndMustInput(String.valueOf(placeFromDataVo.getParkNum()), "停车场车位数", 10000);
        if( apiResponse != null ){
            return apiResponse;
        }

        apiResponse = ValidatorUtils.lengthValidate(placeFromDataVo.getOwnership(), "场馆所有权", 30);
        if( apiResponse != null ){
            return apiResponse;
        }

        apiResponse = ValidatorUtils.lengthValidate(placeFromDataVo.getComment(), "场馆描述", 200);
        if( apiResponse != null ){
            return apiResponse;
        }

        apiResponse = ValidatorUtils.isLat(String.valueOf(placeFromDataVo.getLat()));//纬度校验
        if( apiResponse != null ){
            return apiResponse;
        }

        apiResponse = ValidatorUtils.isLng(String.valueOf(placeFromDataVo.getLng()));//经度校验
        if( apiResponse != null ){
            return apiResponse;
        }

        apiResponse = ValidatorUtils.isYear(placeFromDataVo.getStartBusinessTime());//开业时间校验
        if( apiResponse != null ){
            return apiResponse;
        }

        apiResponse = ValidatorUtils.decimal((placeFromDataVo.getRemainTime()), "运营方经营年限");//运营方经营年限校验
        if( apiResponse != null ){
            return apiResponse;
        }


        apiResponse = ValidatorUtils.isTime(placeFromDataVo.getBusinessHourStart(), "工作日开始营业时间");
        if(apiResponse != null){
            return apiResponse;
        }

        apiResponse = ValidatorUtils.isTime(placeFromDataVo.getBusinessHourEnd(),"工作日结束营业时间");
        if(apiResponse != null){
            return apiResponse;
        }

       /* apiResponse = ValidatorUtils.isTime(placeFromDataVo.getHolidayBusinessHourStart(),"节假日开始营业时间");
        if(apiResponse != null){
            return apiResponse;
        }

        apiResponse = ValidatorUtils.isTime(placeFromDataVo.getHolidayBusinessHourEnd(),"节假日结束营业时间");
        if(apiResponse != null){
            return apiResponse;
        }*/


        if(placeFromDataVo.getBusinessHourStart().compareTo(placeFromDataVo.getBusinessHourEnd()) >= 0){
            return APIResponse.returnFail("工作日营业结束时间" +placeFromDataVo.getBusinessHourEnd() + "小于或开始时间" + placeFromDataVo.getBusinessHourStart());
        }

       /* if(placeFromDataVo.getHolidayBusinessHourStart().compareTo(placeFromDataVo.getHolidayBusinessHourEnd()) >= 0){
            return APIResponse.returnFail("节假日营业结束时间" +placeFromDataVo.getHolidayBusinessHourEnd() + "小于或开始时间" + placeFromDataVo.getHolidayBusinessHourStart());
        }*/

        if(placeFromDataVo.getPlace_attach_list() == null){
            return APIResponse.returnFail("场地图片数量为0。");
        }

        if(placeFromDataVo.getPlace_attach_list() != null){
            if(placeFromDataVo.getPlace_attach_list().size() > 5){
                return APIResponse.returnFail("场地图片数量超过5张。");
            }
        }

        List<Integer> tbBizPlaceCategoryList = placeFromDataVo.getPlaceCategoryList();
        if(tbBizPlaceCategoryList == null || tbBizPlaceCategoryList.size() == 0){
            return APIResponse.returnFail("场地类型为空。");
        }

        List<TbBizPlaceUnitVo> bBizPlaceUnitVoList = placeFromDataVo.getPlace_unit_list();
        if(bBizPlaceUnitVoList != null && bBizPlaceUnitVoList.size() > 0){
            return  this.validatePlaceUnitData(bBizPlaceUnitVoList); // 校验场地数据
        }
        return null;
    }

    /**
     * 场馆数据录入接口
     * @param placeFromDataVo
     * @return
     */
    @Override
    @Transactional
    public APIResponse importPlaceData(PlaceFromDataVo placeFromDataVo) {
        APIResponse apiResponse = validatePlaceData(placeFromDataVo);//参数验证
        if(apiResponse != null){
            return  apiResponse;
        }
        List<TbPlaceImage> tbPlaceImageList = placeFromDataVo.getPlace_attach_list();
        TbBizPlace tbBizPlace = new TbBizPlace();
        TbBizPlaceAttach tbBizPlaceAttach = new TbBizPlaceAttach();
        tbBizPlace.setName(placeFromDataVo.getName());
        tbBizPlace.setAddress(placeFromDataVo.getAddress());
        tbBizPlace.setCityId(placeFromDataVo.getCityId());
        tbBizPlace.setProvinceId(placeFromDataVo.getProvinceId());
        tbBizPlace.setDistrictId(placeFromDataVo.getDistrictId());
        tbBizPlace.setComment(placeFromDataVo.getComment());
        tbBizPlace.setLat(placeFromDataVo.getLat());
        tbBizPlace.setLng(placeFromDataVo.getLng());
        tbBizPlace.setPhone(placeFromDataVo.getPhone());  // 场馆电话
        tbBizPlace.setSupplierId(placeFromDataVo.getSupplierId());
        tbBizPlace.setSourceId(PlaceConstants.SOURCE_PLACE_BUSINESS); // 商务录入，跟原来的数据区分开
        tbBizPlace.setIsMultiUnit(Constants.BYTE_ONE);
        tbBizPlace.setType(Constants.BYTE_ZERO);
        tbBizPlace.setIsOpen(Constants.BYTE_ZERO);
        tbBizPlace.setIsSign(Constants.BYTE_ZERO);
        tbBizPlace.setStatus(1);
        tbBizPlace.setIsRecommend(Constants.BYTE_ZERO);
        tbBizPlace.setIsDelete(0);
        Short s = 0;
        tbBizPlace.setPriority(s);
        tbBizPlace.setIsSign(Constants.BYTE_ZERO);
        tbBizPlace.setType(Constants.BYTE_ZERO);
        tbBizPlace.setUid(placeFromDataVo.getUid());
        tbBizPlace.setBlockindex(PlaceTools.calIndexByLatLon(tbBizPlace.getLat(), tbBizPlace.getLng()));
        tbBizPlace.setSeaAreaType(PlaceConstants.SEA_AREA_TYPE_PUBLIC);
        tbBizPlace.setPlaceScore(0d);
        tbBizPlace.setLowestPrice(0d);
        tbBizPlace.setSignupCount(0);
        tbBizPlace.setCommentCount(0);
        // TODO TbAdminUser tbAdminUser = cacheService.getAdminUser(placeFromDataVo.getUid());
        TbAdminUser tbAdminUser = adminUserMapper.selectByPrimaryKey(placeFromDataVo.getUid());
        if (tbAdminUser != null){
            tbBizPlace.setDeptId(tbAdminUser.getDeptId());
        }

        if(tbPlaceImageList != null && tbPlaceImageList.size() > 0){
            tbBizPlace.setBizPlaceUrl(tbPlaceImageList.get(0).getUrl());
        }
        placeMapper.insert(tbBizPlace);//插入营业场所表

        //Date currentTime=new Date();
        tbBizPlaceAttach.setPlaceId(tbBizPlace.getId()); //从已经插入场馆表中返回的数据获得
        tbBizPlaceAttach.setIsPrimeLocation(placeFromDataVo.getIsPrimeLocation());
        tbBizPlaceAttach.setManageType(placeFromDataVo.getManageType());
        tbBizPlaceAttach.setPlaceLevel(placeFromDataVo.getPlaceLevel());
        tbBizPlaceAttach.setStartBusinessTime(placeFromDataVo.getStartBusinessTime());
        tbBizPlaceAttach.setRemainTime(placeFromDataVo.getRemainTime());
        tbBizPlaceAttach.setIsContainBath(placeFromDataVo.getIsContainBath());
        tbBizPlaceAttach.setIsContainWater(placeFromDataVo.getIsContainWater());
        tbBizPlaceAttach.setIsContainWifi(placeFromDataVo.getIsContainWifi());
        tbBizPlaceAttach.setIsContainHeating(placeFromDataVo.getIsContainHeating());
        tbBizPlaceAttach.setIsContainAc(placeFromDataVo.getIsContainAc());
        tbBizPlaceAttach.setIsContainAdArea(placeFromDataVo.getIsContainAdArea());
        tbBizPlaceAttach.setParkNum(placeFromDataVo.getParkNum());
        tbBizPlaceAttach.setIsParkFree(placeFromDataVo.getIsParkFree());
        tbBizPlaceAttach.setOwnership(placeFromDataVo.getOwnership()); //场馆所有权
        tbBizPlaceAttach.setBusinessHourStart(placeFromDataVo.getBusinessHourStart());
        tbBizPlaceAttach.setBusinessHourEnd(placeFromDataVo.getBusinessHourEnd());
        tbBizPlaceAttach.setHolidayBusinessHourStart(placeFromDataVo.getHolidayBusinessHourStart());
        tbBizPlaceAttach.setHolidayBusinessHourEnd(placeFromDataVo.getHolidayBusinessHourEnd());
        tbBizPlaceAttach.setIsContainPrimeTime(Constants.BYTE_ZERO);
        tbBizPlaceAttach.setIsVip(placeFromDataVo.getIsVip());
        tbBizPlaceAttach.setIsVipHouse(placeFromDataVo.getIsVipHouse());
        tbBizPlaceAttach.setIsTrain(placeFromDataVo.getIsTrain());
        tbBizPlaceAttach.setIsLockerRoom(placeFromDataVo.getIsLockerRoom());
        tbBizPlaceAttach.setPlaceGoods(placeFromDataVo.getPlaceGoods());
        tbBizPlaceAttach.setBookingConsultPhone(placeFromDataVo.getBookingConsultPhone()); // 订场咨询电话
        if(com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(placeFromDataVo.getTrafficInfoList())){
            List<RespBizPlaceTrafficInfo> trafficInfoList = placeFromDataVo.getTrafficInfoList();
            StringBuffer trafficInfoBuffer = new StringBuffer();
            for (RespBizPlaceTrafficInfo respBizPlaceTrafficInfo : trafficInfoList) {
                trafficInfoBuffer.append(respBizPlaceTrafficInfo.getType());
                trafficInfoBuffer.append(":");
                trafficInfoBuffer.append(respBizPlaceTrafficInfo.getDescribe());
                trafficInfoBuffer.append("|");
            }
            if (trafficInfoBuffer.length() > 1){
                tbBizPlaceAttach.setTrafficInfo(trafficInfoBuffer.substring(0,trafficInfoBuffer.length() - 1));
            }
        }

        if(placeFromDataVo.getPlaceCategoryList() != null && placeFromDataVo.getPlaceCategoryList().size() > 0){
            List<Integer> categorySaleTabList = new ArrayList<>();
            categorySaleTabList.addAll(placeFromDataVo.getPlaceCategoryList());
            categorySaleTabList.add(5);
            categorySaleTabList.add(6);
            tbBizPlaceAttach.setSaleTab(org.apache.commons.lang.StringUtils.join(categorySaleTabList.toArray(),","));
        }


        tbBizPlaceAttachMapper.insert(tbBizPlaceAttach);//插入片场附属表
        //插入场地图片资源表

        if(tbPlaceImageList != null && tbPlaceImageList.size() > 0){
            for (TbPlaceImage tbPlaceImage : tbPlaceImageList){
                Byte bb = 1;
                tbPlaceImage.setContentType(bb);
                tbPlaceImage.setTopicId(tbBizPlace.getId());
                tbPlaceImage.setTitle(placeFromDataVo.getName() + "图片");
                tbPlaceImage.setSize(0);
                tbPlaceImageMapper.insert(tbPlaceImage);
            }
        }

        //插入场馆经营范围表
        List<Integer> placeCategoryList = placeFromDataVo.getPlaceCategoryList();
        if(placeCategoryList != null && placeCategoryList.size() > 0){
            for (Integer categoryId : placeCategoryList) {
                TbBizPlaceCategory tbBizPlaceCategory = new TbBizPlaceCategory();
                tbBizPlaceCategory.setPlaceId(tbBizPlace.getId());
                tbBizPlaceCategory.setCategoryId(categoryId);
                tbBizPlaceCategoryMapper.insert(tbBizPlaceCategory);
            }
        }


        //插入拜访记录
        // visitedService.importVisitedRecordByImportPlace(tbBizPlace);
        //插入默认场馆锁定周期，解锁周期
        periodService.importPeriodData(tbBizPlace.getId());

        //更新群id
        MqPlaceGroupId mqPlaceGroupId = new MqPlaceGroupId();
        mqPlaceGroupId.setHead(tbBizPlace.getBizPlaceUrl());
        mqPlaceGroupId.setName(tbBizPlace.getName());
        mqPlaceGroupId.setUid(placeAdminUser);
        mqPlaceGroupId.setId(tbBizPlace.getId());
        updatePlaceGroupId(mqPlaceGroupId);

        // 增加索引
        this.addPlaceIndex(tbBizPlace, null);

        return APIResponse.returnSuccess(tbBizPlace.getId());
    }

    public void addPlaceIndex(TbBizPlace tbBizPlace, List<String> ids){
        // 增加索引
        try{
            this.searchService.addPlaceIndex(tbBizPlace, ids);
        }catch (Exception e){
            logger.error("增加索引失败!");
        }
    }

    /**
     * 根据场馆Id或场地片场Id更新销售计划为无效
     * @param entityType 1：整个场馆  2：指定场地
     * @param entityId
     */
    @Override
    public void updateSalePlanToInvalidate(Integer entityId, Byte entityType) {
        if (entityId == null || entityId ==0){
            return;
        }
        if (Constants.BYTE_ONE == entityType){
            // 删除历史无效数据
            vPlaceMapper.delInvalidSalePlan(entityId);
        }
        vPlaceMapper.updateSalePlanToInvalidate(entityId, entityType, null);
    }

    /**
     * 根据场馆Id和运动项目id更新销售计划为无效
     * @param placeId
     * @param categroyId
     */
    public void updateSalePlanToInvalidateByCategroyId(Integer placeId, Integer categroyId) {
        if (placeId == null || placeId ==0){
            return;
        }
        // 删除历史无效数据
        vPlaceMapper.delInvalidSalePlan(placeId);
        vPlaceMapper.updateSalePlanToInvalidate(placeId, Constants.BYTE_ONE, categroyId);
    }


    /**
     * 根据场馆Id更新销售计划模板为无效
     * @param placeId
     * @param categoryId
     */
    @Override
    public void updateSalePlanMainToInvalidate(Integer placeId, Integer categoryId) {
        Map<String,Object> map = new HashMap<>();
        map.put("placeId", placeId);
        map.put("categoryId", categoryId);
        vPlaceMapper.updateSalePlanMainToInvalidate(placeId, categoryId);
    }

    public Integer updatePlaceGroupId(MqPlaceGroupId mqPlaceGroupId){
        Map<String,Object> paramMap = new HashMap();
        paramMap.put("groupname",mqPlaceGroupId.getName());               //群组名称
        paramMap.put("ispublic",0);                        //公开群
        paramMap.put("maxusers",1000);                     //群组成员最大数
        paramMap.put("approval",1);                        //不需要批准
        paramMap.put("type",5);                            //场馆类型
        paramMap.put("groupdescriptions",mqPlaceGroupId.getName());       //群组描述
        paramMap.put("owner",mqPlaceGroupId.getUid());                         //请求用户的Uid  678测试可用
        paramMap.put("ver","1.1.0000");
        paramMap.put("protocol_ver","1.0");
        paramMap.put("currentUid",mqPlaceGroupId.getUid());
        paramMap.put("head",mqPlaceGroupId.getHead());

        String json = JSON.toJSONString(paramMap);

        String result = null;
        try {
            result = HttpClientUtils.postJson(cAddress + "/IM/createGroup.api", json);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String data = jsonObject.getString("data");
            JSONObject jsondata = JSONObject.parseObject(data);
            JSONArray jsonArray  = jsondata.getJSONArray("groupinfo");
            Object[] arrayObjects = jsonArray.toArray();
            PlaceGroupInfo placeGroupInfo = JSON.parseObject(arrayObjects[0].toString(), PlaceGroupInfo.class);
            logger.info("获取场馆聊天群号信息：" + result);
            TbBizPlace tbBizPlace = new TbBizPlace();
            tbBizPlace.setId(mqPlaceGroupId.getId());
            tbBizPlace.setGroupId(placeGroupInfo.getGroupid());
            placeMapper.updateByPrimaryKeySelective(tbBizPlace);

            APIResponse  apiResponse =  getPlaceData(mqPlaceGroupId.getId());
            TbBizPlace tbBizPlaceTemp = (TbBizPlace)apiResponse.getData();
            try{
                this.addPlaceIndex(tbBizPlaceTemp, null);
            }catch (Exception e){
                logger.error("增加索引失败!");
                return 0;
            }
            return 1;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    @Override
    @Transactional
    public APIResponse updatePlaceUnitData(TbBizPlaceUnitVo tbBizPlaceUnitVo) {

        TbBizPlaceUnitExample tbBizPlaceUnitExample = new TbBizPlaceUnitExample();
        TbBizPlaceUnitExample.Criteria tbBizPlaceUnitCriteria = tbBizPlaceUnitExample.createCriteria();

        tbBizPlaceUnitCriteria.andPlaceIdEqualTo(tbBizPlaceUnitVo.getPlaceId());
        tbBizPlaceUnitCriteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        tbBizPlaceUnitCriteria.andIdNotEqualTo(tbBizPlaceUnitVo.getId());
        tbBizPlaceUnitCriteria.andCategoryIdEqualTo(tbBizPlaceUnitVo.getCategoryId());
        List<TbBizPlaceUnit> tbBizPlaceUnitList = placeUnitMapper.selectByExample(tbBizPlaceUnitExample);
        if(tbBizPlaceUnitList !=null && tbBizPlaceUnitList.size()>0){
            for(TbBizPlaceUnit tbBizPlaceUnit : tbBizPlaceUnitList){
                if(tbBizPlaceUnit.getName().equals(tbBizPlaceUnitVo.getName())){
                    return APIResponse.returnFail("场地名已经存在！");
                }
            }
        }

        List<TbBizPlaceUnitTime> tbBizPlaceUnitTimes = tbBizPlaceUnitVo.getPlace_unit_time_list();
        if(tbBizPlaceUnitTimes != null && tbBizPlaceUnitTimes.size() > 0){
            List<TbBizPlaceUnitVo> bBizPlaceUnitVoList = new ArrayList<TbBizPlaceUnitVo>();
            bBizPlaceUnitVoList.add(tbBizPlaceUnitVo);
            APIResponse apiResponse = validatePlaceUnitData(bBizPlaceUnitVoList);
            if(apiResponse != null){
                return apiResponse;
            }

            //在片场时间表中删除相关片场的所有时间
            TbBizPlaceUnitTimeExample tbBizPlaceUnitTimeExample = new TbBizPlaceUnitTimeExample();
            TbBizPlaceUnitTimeExample.Criteria tbBizPlaceUnitTimeCriteria = tbBizPlaceUnitTimeExample.createCriteria();
            tbBizPlaceUnitTimeCriteria.andPlaceIdEqualTo(tbBizPlaceUnitVo.getPlaceId());
            tbBizPlaceUnitTimeCriteria.andPlaceUnitIdEqualTo(tbBizPlaceUnitVo.getId());
            placeUnitTimeMapper.deleteByExample(tbBizPlaceUnitTimeExample);

            //重新插入片场时间
            boolean isPrimeTime = false;
            for(TbBizPlaceUnitTime tbBizPlaceUnitTime : tbBizPlaceUnitTimes){
                if(tbBizPlaceUnitTime.getIsPrimeTime() == 1){
                    isPrimeTime = true;
                }
                String time_length = "00:00:00";
                try {
                    time_length = TimeUtils.subtractTime(tbBizPlaceUnitTime.getStartTime(), tbBizPlaceUnitTime.getEndTime());
                }
                catch (ParseException e){
                    e.printStackTrace();
                }
                tbBizPlaceUnitTime.setTimeLength(TimeUtils.timeToHour(time_length));
                tbBizPlaceUnitTime.setPlaceUnitId(tbBizPlaceUnitVo.getId());
                tbBizPlaceUnitTime.setPlaceId(tbBizPlaceUnitVo.getPlaceId());
                placeUnitTimeMapper.insert(tbBizPlaceUnitTime);
            }

            TbBizPlaceUnitStatistics tbBizPlaceUnitStatistics = getPlaceUnitStatisticsBean(tbBizPlaceUnitTimes);
            unitStatisticsMapper.updateByPrimaryKeySelective(tbBizPlaceUnitStatistics); //更新片场时间统计表

            //更新场馆黄金时间属性
            if(isPrimeTime){
                TbBizPlaceAttach tbBizPlaceAttach = new TbBizPlaceAttach();
                tbBizPlaceAttach.setIsContainPrimeTime((byte) 1);
                TbBizPlaceAttachExample tbBizPlaceAttachExample = new TbBizPlaceAttachExample();
                TbBizPlaceAttachExample.Criteria tbBizPlaceAttachCriteria = tbBizPlaceAttachExample.createCriteria();
                tbBizPlaceAttachCriteria.andPlaceIdEqualTo(tbBizPlaceUnitVo.getPlaceId());
                tbBizPlaceAttachMapper.updateByExampleSelective(tbBizPlaceAttach,tbBizPlaceAttachExample);
            }

        }
        TbBizPlaceUnit tbBizPlaceUnit = new TbBizPlaceUnit();
        tbBizPlaceUnit.setName(tbBizPlaceUnitVo.getName());
        tbBizPlaceUnit.setId(tbBizPlaceUnitVo.getId());
        tbBizPlaceUnit.setPlaceId(tbBizPlaceUnitVo.getPlaceId());
        tbBizPlaceUnit.setCategoryId(tbBizPlaceUnitVo.getCategoryId());
        tbBizPlaceUnit.setComment(tbBizPlaceUnitVo.getComment());
        tbBizPlaceUnit.setFieldScale(tbBizPlaceUnitVo.getFieldScale());
        tbBizPlaceUnit.setLightType(tbBizPlaceUnitVo.getLightType());
        tbBizPlaceUnit.setPlaceUnitTexture(tbBizPlaceUnitVo.getPlaceUnitTexture());
        tbBizPlaceUnit.setPlaceUnitType(tbBizPlaceUnitVo.getPlaceUnitType());
        int flag = placeUnitMapper.updateByPrimaryKeySelective(tbBizPlaceUnit);

        //Todo 修改tb_biz_place_unit_sale_plan tb_biz_place_unit_sale_plan_main 片场名称
        if (flag == 1){
            updateExecutorPlaceUnitNameService.execute(new ModifyPlaceUnitNameThread(tbBizPlaceUnitSalePlanMapper,tbBizPlaceUnitSalePlanMainMapper,tbBizPlaceUnitVo.getName(),tbBizPlaceUnitVo.getId()));
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 获取片场黄金时间统计的javabean
     * @param tbBizPlaceUnitTimeList   每个片场下的时间列表（包含营业时间和黄金时间）
     * @return
     */
    public  TbBizPlaceUnitStatistics getPlaceUnitStatisticsBean(List<TbBizPlaceUnitTime> tbBizPlaceUnitTimeList) {
        try {
            String week_hour_num = "00:00:00";
            String week_prime_hour_num = "00:00:00";
            TbBizPlaceUnitStatistics tbBizPlaceUnitStatistics = new TbBizPlaceUnitStatistics();
            Map<Integer,String> timeMap = new HashMap<Integer, String>();
            timeMap.put(1,"00:00:00");
            timeMap.put(0,"00:00:00");
            if(tbBizPlaceUnitTimeList != null && tbBizPlaceUnitTimeList.size() > 0){
                tbBizPlaceUnitStatistics.setPlaceId(tbBizPlaceUnitTimeList.get(0).getPlaceId());
                tbBizPlaceUnitStatistics.setPlaceUnitId(tbBizPlaceUnitTimeList.get(0).getPlaceUnitId());
                for (TbBizPlaceUnitTime tbBizPlaceUnitTime : tbBizPlaceUnitTimeList){
                    String countTime = TimeUtils.subtractTime(tbBizPlaceUnitTime.getStartTime(), tbBizPlaceUnitTime.getEndTime());
                    String tempTime = TimeUtils.addTime(timeMap.get(tbBizPlaceUnitTime.getIsPrimeTime()), countTime);
                    timeMap.put(tbBizPlaceUnitTime.getIsPrimeTime(),tempTime);
                }

                week_prime_hour_num = timeMap.get(1);
                week_hour_num = timeMap.get(0);
                week_hour_num = TimeUtils.addTime(week_hour_num, week_prime_hour_num);
                double weekPrimeHourNum = TimeUtils.timeToHour(week_prime_hour_num);
                double weekHourNum = TimeUtils.timeToHour(week_hour_num);
                tbBizPlaceUnitStatistics.setWeekPrimeHourNum(BigDecimal.valueOf(weekPrimeHourNum));
                tbBizPlaceUnitStatistics.setWeekHourNum(BigDecimal.valueOf(weekHourNum));
            }

            return tbBizPlaceUnitStatistics;
        }
        catch (ParseException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取场馆信息
     * @param placeId
     * @return
     */
    @Override
    public APIResponse getPlaceData(int placeId) {
        try {
            TbBizPlace tbBizPlace = placeMapper.selectByPrimaryKey(placeId);
            return APIResponse.returnSuccess(tbBizPlace);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return  APIResponse.returnFail(ApiResponseEnum.RESOURCE_NOT_FOUND);
    }

    /**
     * 校验场地信息
     * @param placeUnitVos
     * @return
     */
    public APIResponse validatePlaceUnitData(List<TbBizPlaceUnitVo> placeUnitVos) {
        HashMap<String,String> result = new HashMap<String,String>();
        APIResponse apiResponse = null;
        for (TbBizPlaceUnitVo tbBizPlaceUnitVo : placeUnitVos){//遍历场地列表
            apiResponse = ValidatorUtils.lengthValidateMustInput(tbBizPlaceUnitVo.getName(), "场地名称", 20);

            if( apiResponse != null ){
                return apiResponse;
            }

            if(result.containsKey(tbBizPlaceUnitVo.getName())){
                return APIResponse.returnFail("场地名称" + tbBizPlaceUnitVo.getName() + "重复");
            }
            else{
                result.put(tbBizPlaceUnitVo.getName(),"场地名称");
            }

            apiResponse = ValidatorUtils.lengthValidate(tbBizPlaceUnitVo.getComment(), "场地备注", 50);

            if( apiResponse != null ){
                return apiResponse;
            }

            List<TbBizPlaceUnitTime> tbBizPlaceUnitTimeList = tbBizPlaceUnitVo.getPlace_unit_time_list();

            if(tbBizPlaceUnitTimeList != null && tbBizPlaceUnitTimeList.size() > 0){
                for (int i = 0; i < tbBizPlaceUnitTimeList.size(); i++) {
                    TbBizPlaceUnitTime tbBizPlaceUnitTime = tbBizPlaceUnitTimeList.get(i);
                    String EndTime = tbBizPlaceUnitTime.getEndTime();
                    String StartTime = tbBizPlaceUnitTime.getStartTime();

                    apiResponse = ValidatorUtils.isTime(StartTime,getCommonDataCache(tbBizPlaceUnitTime.getTimeType()) +"的开始时间" + StartTime);
                    if(apiResponse != null){
                        return apiResponse;
                    }

                    apiResponse = ValidatorUtils.isTime(EndTime,getCommonDataCache(tbBizPlaceUnitTime.getTimeType()) + "的结束时间" + EndTime);
                    if(apiResponse != null){
                        return apiResponse;
                    }

                    if(StartTime.compareTo(EndTime) >= 0){
                        return APIResponse.returnFail(getCommonDataCache(tbBizPlaceUnitTime.getTimeType())+"的结束时间" +EndTime + "小于或等于开始时间" + StartTime);
                    }

                }

                for (int i = 0; i < tbBizPlaceUnitTimeList.size()-1; i++) {
                    TbBizPlaceUnitTime tbBizPlaceUnitTime1 = tbBizPlaceUnitTimeList.get(i);
                    for (int j = i + 1; j < tbBizPlaceUnitTimeList.size(); j++) {
                        TbBizPlaceUnitTime tbBizPlaceUnitTime2 = tbBizPlaceUnitTimeList.get(j);
                        if(tbBizPlaceUnitTime1.getTimeType().equals(tbBizPlaceUnitTime2.getTimeType())){
                            if(TimeUtils.isOverLaps(tbBizPlaceUnitTime1.getStartTime(), tbBizPlaceUnitTime1.getEndTime(), tbBizPlaceUnitTime2.getStartTime(), tbBizPlaceUnitTime2.getEndTime(), "HH:mm") ){
                                return APIResponse.returnFail(getCommonDataCache(tbBizPlaceUnitTime1.getTimeType())+"的时段"+ tbBizPlaceUnitTime1.getStartTime()+ "-"+ tbBizPlaceUnitTime1.getEndTime()+"和"+ tbBizPlaceUnitTime2.getStartTime()+ "-"+ tbBizPlaceUnitTime2.getEndTime()+"有重叠!");
                            }
                        }
                    }
                }

            }
        }
        return null;
    }

    public String getCommonDataCache(String key){
        if(placeCommonDataMap.size() == 0){//初始化时加载数据库配置表中数据到placeCommonDataMap中
            APIResponse<PlaceCommonDataVo> apiResponse = getPlaceCommonData();
            PlaceCommonDataVo placeCommonDataVo = apiResponse.getData();
            List<Dict> placeCommonDataList = new ArrayList<Dict>();

            placeCommonDataList.addAll(placeCommonDataVo.getBadminton_unit_texture());
            placeCommonDataList.addAll(placeCommonDataVo.getBadminton_unit_type());
            placeCommonDataList.addAll(placeCommonDataVo.getBasketball_unit_texture());
            placeCommonDataList.addAll(placeCommonDataVo.getBasketball_unit_type());
            placeCommonDataList.addAll(placeCommonDataVo.getFootball_field_scale());
            placeCommonDataList.addAll(placeCommonDataVo.getFootball_unit_texture());
            placeCommonDataList.addAll(placeCommonDataVo.getFootball_unit_type());
            placeCommonDataList.addAll(placeCommonDataVo.getTennis_unit_texture());
            placeCommonDataList.addAll(placeCommonDataVo.getTennis_unit_type());
            placeCommonDataList.addAll(placeCommonDataVo.getTime_type());
            placeCommonDataList.addAll(placeCommonDataVo.getManage_type());
            placeCommonDataList.addAll(placeCommonDataVo.getLight_type());

            List<Cagetory> cagetoryList = placeCommonDataVo.getCagetory_list();
            List<Dict> dictList = new ArrayList<>();
            for (Cagetory cagetory : cagetoryList) {
                Dict dict = new Dict();
                dict.setDataKey("cagetory"+cagetory.getId().toString());
                dict.setDataValue(cagetory.getName());
                dictList.add(dict);
            }
            placeCommonDataList.addAll(dictList);

            for(Dict dict : placeCommonDataList){
                if (null != dict.getDataKey()){
                    placeCommonDataMap.put(dict.getDataKey(), dict.getDataValue());
                }
            }
        }
        if (null == key){
            return null;
        }
        return placeCommonDataMap.get(key);

    }

    public APIResponse getPlaceCommonData() {
        PlaceCommonDataVo placeCommonDataVo = new PlaceCommonDataVo();
        Class<PlaceCommonDataVo> cls = PlaceCommonDataVo.class;
        Map<String,String> condition = new HashMap<String,String>();

        condition.put("网球场地类型","tennis_unit_type");
        condition.put("羽毛球场地类型","badminton_unit_type");
        condition.put("篮球场地类型","basketball_unit_type");
        condition.put("足球场地类型","football_unit_type");

        condition.put("网球场地材质","tennis_unit_texture");
        condition.put("羽毛球场地材质","badminton_unit_texture");
        condition.put("篮球场地材质","basketball_unit_texture");
        condition.put("足球场地材质","football_unit_texture");

        condition.put("灯光类型","light_type");
        condition.put("时间类型","time_type");
        condition.put("场馆属性","manage_type");
        condition.put("足球场地规模","football_field_scale");
        condition.put("篮球场地规模","basketball_field_scale");

        try {
            Set<Map.Entry<String,String>> set = condition.entrySet();
            for (Map.Entry<String,String> map : set){
                DictExample dictExample = new DictExample();
                DictExample.Criteria dictCriteria = dictExample.createCriteria();
                dictCriteria.andTagEqualTo(map.getKey());
                Field field = cls.getDeclaredField(map.getValue());
                field.setAccessible(true);
                List<Dict> result = this.dictMapper.selectDataValueByExample(dictExample);
                field.set(placeCommonDataVo,result);
            }
        }
        catch (Exception e){
            e.printStackTrace();
            APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
        }

        CagetoryExample cagetoryExample = new CagetoryExample();
        CagetoryExample.Criteria cagetoryCriteria = cagetoryExample.createCriteria();
        cagetoryCriteria.andIdLessThanOrEqualTo(4);
        List<Cagetory> cagetoryList = this.categoryMapper.selectNameByExample(cagetoryExample);
        placeCommonDataVo.setCagetory_list(cagetoryList);

        return APIResponse.returnSuccess(placeCommonDataVo);
    }

    @Override
    public APIResponse getFieldScales() {
        RespPlaceFieldScales fieldScales = new RespPlaceFieldScales();
        Class<RespPlaceFieldScales> cls = RespPlaceFieldScales.class;

        Map<String,String> condition = new HashMap<String,String>();

        condition.put("足球场地规模","footballFieldScales");
        condition.put("篮球场地规模","basketballFieldScales");

        try {
            Set<Map.Entry<String,String>> set = condition.entrySet();
            for (Map.Entry<String,String> map : set){
                DictExample dictExample = new DictExample();
                DictExample.Criteria dictCriteria = dictExample.createCriteria();
                dictCriteria.andTagEqualTo(map.getKey());
                List<Dict> result = this.dictMapper.selectDataValueByExample(dictExample);
                if(result != null) {
                    List<RespFieldScale> fss = new ArrayList<>();
                    for (Dict dict : result) {
                        RespFieldScale fs = new RespFieldScale(dict.getDataValue(), dict.getDataKey());
                        fss.add(fs);
                    }
                    Field field = cls.getDeclaredField(map.getValue());
                    field.setAccessible(true);
                    field.set(fieldScales, fss);
                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
            APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
        }

        return APIResponse.returnSuccess(fieldScales);
    }

    @Override
    public PageObj<List<TbBizPlaceUnit>> getAllPlaceUnitList(ReqPlaceUnitSearch reqPlaceUnitSearch) {
        Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        if (reqPlaceUnitSearch != null){
            pageNum = reqPlaceUnitSearch.getPageNum();
            pageSize = reqPlaceUnitSearch.getPageSize();
            int total = placeUnitListMapper.countPlaceUnitList(reqPlaceUnitSearch);
            reqPlaceUnitSearch.setPage(new Page(pageNum * pageSize, pageSize, total));
            List<TbBizPlaceUnit> records = placeUnitListMapper.selectPlaceUnitList(reqPlaceUnitSearch);
            PageObj<List<TbBizPlaceUnit>> result = PageObj.create(total, pageNum, pageSize, records);
            return result;
        } else {
            return null;
        }
    }


    /**
     * 查询场馆数据，用于初始化列表
     * @param map
     * @return
     */
    @Override
    public List<TbBizPlace> getPlaceListForSolrIndex(Map map) {
        Integer pageNum = 0;
        Integer pageSize = 99999999;
        if (map.containsKey("pageNum")){
            pageNum = (Integer)map.get("pageNum");
        }
        if (map.containsKey("pageSize")){
            pageSize = (Integer)map.get("pageSize");
        }
        TbBizPlaceExample example = new TbBizPlaceExample();
        example.createCriteria().andIsDeleteEqualTo((int)Constants.IS_DELETE_FALSE).andSourceIdEqualTo(PlaceConstants.SOURCE_PLACE_BUSINESS);
        int total = placeMapper.countByExample(example);
        if (null != pageNum && pageSize != null){
            example.setPage(new Page(pageNum * pageSize, pageSize, total));
        }
        List<TbBizPlace> records = placeMapper.selectByExample(example);
        return records;
    }

    @Override
    public void isExsit(Integer placeId) {
        TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
        example.createCriteria().andPlaceIdEqualTo(placeId);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans= placeUnitSalePlanMapper.selectByExample(example);
        if (com.alibaba.dubbo.common.utils.CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)){
            PlaceSearchService placeSearchService = new PlaceSearchServiceImpl(solrUrl);
            placeSearchService.deleteDocById(placeId, PlaceConstants.SOLR_INDEX_PLACE);
        }
    }

    /**
     * 设置商务代表状态
     * @param place
     */
    public void setRepresentStats (TbBizPlace place){
        TbBizPlaceRepresentExample rExample=new TbBizPlaceRepresentExample();
        TbBizPlaceRepresentExample.Criteria rCriteria=rExample.createCriteria();
        TbBizPlaceRepresent vo=new TbBizPlaceRepresent();
        rCriteria.andPlaceIdEqualTo(place.getId());
        rCriteria.andIsEffectiveEqualTo(PlaceConstants.IS_EFFECTIVE_YES);
        vo.setIsEffective(PlaceConstants.IS_EFFECTIVE_NO);
        tbBizPlaceRepresentMapper.updateByExampleSelective(vo,rExample);
    }

    @Override
    public List<TbBizPlace> getPlaceList(Map map) {
        return pMapper.getPlaceList(map);
    }


    /**
     * 根据项目类别等查找场馆信息
     * @param reqVo
     * @return
     */
    @Override
    public PageObj<List<RespPlaceInfo>> getPlaceListByCategoryId(ReqPlaceSearch reqVo) {
        Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        if (!StringUtils.isEmpty(reqVo.getName())) {
            reqVo.setName("%" + reqVo.getName().trim() + "%");
        }else{
            reqVo.setName(null);
        }
        if (reqVo!=null){
            pageNum=reqVo.getPageNum();
            pageSize=reqVo.getPageSize();
        }
        int  total = vPlaceMapper.getPlaceListByCategoryIdCount(reqVo);
        reqVo.setPage(new Page(pageNum * pageSize, pageSize, total));
        List<RespPlaceInfo> list=  vPlaceMapper.getPlaceListByCategoryId(reqVo);

        PageObj<List<RespPlaceInfo>> result = PageObj.create(total, pageNum, pageSize, list);
        return result;
    }

    @Override
    public List<TbBizPlaceUnitSalePlan> getPlaceUnitSalePlanBySaleId(List saleidList) {
        TbBizPlaceUnitSalePlanExample example =new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria criteria=example.createCriteria();
        criteria.andSaleIdIn(saleidList);
        List<TbBizPlaceUnitSalePlan> list=tbBizPlaceUnitSalePlanMapper.selectByExample(example);
            return list;
    }

    /**
     * 删除无效的销售计划
     * @param placeId
     */
    public void delInvalidSalePlan(Integer placeId){
        vPlaceMapper.delInvalidSalePlan(placeId);
    }

    @Override
    public List<TbBizPlace> getPlaceBySupplierId(Integer supplierId) {
        TbBizPlaceExample example =new TbBizPlaceExample();
        TbBizPlaceExample.Criteria criteria=example.createCriteria();
        criteria.andSupplierIdEqualTo(supplierId);
        return tbBizPlaceMapper.selectByExample(example);
    }

    /**
     * 删除场地时段
     * @param placeId
     * @param placeUnitIdList
     */
    @Override
    public void deletePlaceUnitTime(Integer placeId, List<Integer> placeUnitIdList) {
        if (null == placeId){
            return;
        }
        if (null == placeUnitIdList || placeUnitIdList.size() == 0){
            return;
        }
        //在片场时间表中删除相关片场的所有时间
        TbBizPlaceUnitTimeExample tbBizPlaceUnitTimeExample = new TbBizPlaceUnitTimeExample();
        TbBizPlaceUnitTimeExample.Criteria tbBizPlaceUnitTimeCriteria = tbBizPlaceUnitTimeExample.createCriteria();
        tbBizPlaceUnitTimeCriteria.andPlaceIdEqualTo(placeId);
        tbBizPlaceUnitTimeCriteria.andPlaceUnitIdIn(placeUnitIdList);
        placeUnitTimeMapper.deleteByExample(tbBizPlaceUnitTimeExample);
    }

    /**
     * 已售场地由整点变更为半点
     * @param placeId
     * @param categoryId
     */
    @Override
    public void splitSalePlanAlreadyBooked(Integer placeId, Integer categoryId) throws Exception{
        List<TbBizPlaceUnitSalePlan> unitSalePlanList = this.getUnitSalePlanAlreadyBooked(placeId, categoryId);
        List<TbBizPlaceUnitSalePlan> insertSalePlan = new ArrayList<TbBizPlaceUnitSalePlan>();
        for (TbBizPlaceUnitSalePlan unitSalePlan : unitSalePlanList){
            TbBizPlaceUnitSalePlan firstSegment = new TbBizPlaceUnitSalePlan();
            TbBizPlaceUnitSalePlan secondSegment = new TbBizPlaceUnitSalePlan();
            BeanUtils.copyProperties(firstSegment, unitSalePlan);
            Date middleTime = PlaceUtil.getMiddleTime(unitSalePlan.getStartTime());
            firstSegment.setStartTime(unitSalePlan.getStartTime());
            firstSegment.setEndTime(middleTime);
            firstSegment.setId(null);
            firstSegment.setCreateTime(new Date());
            firstSegment.setSaleId(CommonUtils.createSaleID(firstSegment.getPlaceUnitId(), firstSegment.getDate(),
                    firstSegment.getStartTime(), firstSegment.getEndTime()));
            firstSegment.setDestSaleId(unitSalePlan.getSaleId()); // 与拆分前的销售计划saleId 做关联
            insertSalePlan.add(firstSegment);

            BeanUtils.copyProperties(secondSegment, unitSalePlan);
            secondSegment.setStartTime(middleTime);
            secondSegment.setId(null);
            secondSegment.setSaleId(CommonUtils.createSaleID(secondSegment.getPlaceUnitId(), secondSegment.getDate(),
                    secondSegment.getStartTime(), secondSegment.getEndTime()));
            secondSegment.setCreateTime(new Date());
            secondSegment.setDestSaleId(unitSalePlan.getSaleId()); // 与拆分前的销售计划saleId 做关联
            insertSalePlan.add(secondSegment);
            //tbBizPlaceUnitSalePlanMapper.insert(firstSegment);
            //tbBizPlaceUnitSalePlanMapper.insert(secondSegment);
        }
        if (null != insertSalePlan && insertSalePlan.size() > 0){
            salePlanMapper.batchInsertSalePlan(insertSalePlan);
        }
    }

    /**
     * 删除指定场馆、指定日期的销售计划
     * @param placeId
     * @param date
     */
    @Override
    public void deleteSalePlanByPlaceAndDate(Integer placeId, Date date) {
        if (placeId == null || date == null){
            return;
        }
        String strDate = DateUtils.changeDateToString(date);
        vPlaceMapper.deleteSalePlanByPlaceAndDate(placeId,strDate);
    }

    /**
     * 场地同步价格信息（退款、取消预订等价格变更时做检查）
     * @param placeOrderId
     */
    @Async
    public void syncSalePlanPriceForRefundOrder(String placeOrderId){
        TbBizPlaceOrder tbBizPlaceOrder = this.getPlaceOrderByPlaceOrderId(placeOrderId);
        Byte useType = tbBizPlaceOrder.getUseType();
        List<String> salePlanId = new ArrayList<String>();
        if (PlaceConstants.ORDER_USE_BILLING == useType||
            PlaceConstants.ORDER_USE_BLOCK_BOOKING == useType||
                PlaceConstants.ORDER_USE_APP_BILLING == useType){
            // 场地订单
            List<TbBizPlaceOrderItem> orderItemList = this.getPlaceOrderItemList(placeOrderId);
            for (TbBizPlaceOrderItem item : orderItemList){
                salePlanId.add(item.getSaleId());
            }
        }
        if (PlaceConstants.ORDER_USE_SHOPPING_CART == useType){
            // 购物车订单
            List<TbBizPlaceOrderItem> orderItemList = this.getPlaceOrderItemList(placeOrderId);
            for (TbBizPlaceOrderItem item : orderItemList){
                if (PlaceConstants.ORDER_USE_BILLING == item.getUseType() ||
                        PlaceConstants.ORDER_USE_APP_BILLING == item.getUseType()){
                    salePlanId.add(item.getSaleId());
                }
            }
        }
        if (salePlanId.size() ==0){
            return;
        }
        List<TbBizPlaceUnitSalePlan> salePlanList = this.getPlaceUnitSalePlanBySaleId(salePlanId);
        for (TbBizPlaceUnitSalePlan salePlan : salePlanList){
            TbBizPlaceUnitSalePlanMain salePlanMain = this.getPlaceSalePlanByTemplateId(salePlan.getSalePlanMainId());
            if (salePlan.getPrice().compareTo(salePlanMain.getPrice()) != 0 ||
                    salePlan.getMemberPrice().compareTo(salePlanMain.getMemberPrice()) != 0 ){
                // 价格有变更
                salePlan.setPrice(salePlanMain.getPrice());
                salePlan.setMemberPrice(salePlanMain.getMemberPrice());
                this.updatePlaceUnitSalePlanBykey(salePlan); // TODO 改成批量
            }
        }
    }

    public List<TbBizPlaceOrderItem> getPlaceOrderItemList(String placeOrderId) {
        TbBizPlaceOrderItemExample example = new TbBizPlaceOrderItemExample();
        TbBizPlaceOrderItemExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceOrderIdEqualTo(placeOrderId);
        List<TbBizPlaceOrderItem> result = tbBizPlaceOrderItemMapper.selectByExample(example);
        return result;
    }

    private TbBizPlaceOrder getPlaceOrderByPlaceOrderId(String placeOrderId) {
        TbBizPlaceOrderExample example = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceOrderIdEqualTo(placeOrderId);
        List<TbBizPlaceOrder> list = tbBizPlaceOrderMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }


    /**
     * 根据Id查询销售计划模板
     * @param salePlanMainId
     * @return
     */
    @Override
    public TbBizPlaceUnitSalePlanMain getPlaceSalePlanByTemplateId(Integer salePlanMainId) {
        return placeUnitSalePlanMainMapper.selectByPrimaryKey(salePlanMainId);
    }


    /**
     * 按主键更新销售计划
     * @param salePlan
     */
    @Override
    public void updatePlaceUnitSalePlanBykey(TbBizPlaceUnitSalePlan salePlan) {
        placeUnitSalePlanMapper.updateByPrimaryKey(salePlan);
    }

    /**
     * 查询所有已经锁定库存的销售计划
     * @param placeId
     * @param categoryId
     * @return
     */
    public List<TbBizPlaceUnitSalePlan> getUnitSalePlanAlreadyBooked(Integer placeId, Integer categoryId) {
        TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria tbBizPlaceUnitTimeCriteria = tbBizPlaceUnitSalePlanExample.createCriteria();
        tbBizPlaceUnitTimeCriteria.andPlaceIdEqualTo(placeId);
        tbBizPlaceUnitTimeCriteria.andCategoryIdEqualTo(categoryId);
        tbBizPlaceUnitTimeCriteria.andDateGreaterThanOrEqualTo(new Date());
        tbBizPlaceUnitTimeCriteria.andStatusNotEqualTo(PlaceConstants.PLACE_PREORDER_STATUS); // 排除未预定的（包含已预订、正在锁定、后台锁定状态）
        return tbBizPlaceUnitSalePlanMapper.selectByExample(tbBizPlaceUnitSalePlanExample);
    }

	@Override
	public TbBizPlaceUnitSalePlan selectUnitSalePlanBySaleId(String saleId) {
		TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
		tbBizPlaceUnitSalePlanExample.createCriteria().andSaleIdEqualTo(saleId);
		List<TbBizPlaceUnitSalePlan> unitSalePlanList = 
				tbBizPlaceUnitSalePlanMapper.selectByExample(tbBizPlaceUnitSalePlanExample);
		if (!CollectionUtils.isEmpty(unitSalePlanList)) {
			return  unitSalePlanList.get(0);
		}
		return null;
	}

}
